3

Suppose I have Users data that store array of pet in String datatype

[
  #<User id: 1, name: "John", pets: "---\n- cat\n- dog\n- bunny\n- ''\n">,
  #<User id: 2, name: "Pete", pets: "---\n- dog\n- bunny\n- ''\n">,
  #<User id: 3, name: "Jack", pets: "---\n- cat\n- ''\n">,
  #<User id: 4, name: "Kurt", pets: "---\n- cat\n- bunny\n- ''\n">
]

Can i get all users that has a cat? Maybe something like User.find_all_by... or User.where(....) or anything that return as a relation? So i can order with active record query.

I know i can get all users that has a cat with

User.all.select{|s| YAML.load(s.pets).include?'cat'}

, but it convert to array that cannot be ordered with active record query.

thx for helping.

1

2 Answers 2

3

You could use simple SQL to see if 'cat' shows up in the serialized column.

User.where('pets LIKE "%cat%"').all

Sign up to request clarification or add additional context in comments.

1 Comment

it will also retrieves "catfish"
1

You need to normalize your data, add Pet model and set has_and_belongs_to_many association between theese models.

1 Comment

for some reason, i prevent to add another model. it's ok for me, if there's no better solution. thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.