Rails Active Post Request, Serialized Array

Suppose I have User data that stores an array of pets in Stat 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 who have a cat? Maybe something like User.find_all_by...

or User.where(....)

or something that comes back as a relation? Therefore, I can order an active write request.

I know I can get all users who have a cat with

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

      

but it converts to an array which cannot be ordered with an active write request.

thanks for the help.

+3


source to share


2 answers


You can use plain SQL to see if "cat" appears on the serialized column.



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

+3


source


You need to normalize your data, add a Pet model, and establish a has_and_belongs_to_many relationship between these models.



+1


source







All Articles