Daniel B Daniel B - 4 months ago 19
Ruby Question

Finding a value in a serialized model array

I am not sure if an explanation is already documented on this, maybe im asking the wrong question, but i hope someone can help me with this issue.

I am looking for a value within a model array. My model looks like this:

class Product < ActiveRecord::Base
# product_category :text
serialize :product_category, Array
end


An example of an entry:

#<Product:0x0055cd0c1382b8> {
:id => 42266,
:product_category => [
[0] 8, [1] 3
]
}


I need to find all products that belong to
product_category
3 or a combination of 3 and other categories.

I tried something like

ap Product.where(product_category: [8])


but this doesnt return anything.

If this question was already asked, please forward me to the right answer. If not, any time put towards helping me is greatly appreciated.

Running:


  • Rails 4.2.4

  • Ruby 2.3.1.p112

  • SQLite3


Answer

Though I would not recommend to do this, but a patch work would be as follows

Product.all.select { |m| m.product_category.include? '3' }

Don't use #serialize for any data that later on you need to query