Daniel B Daniel B - 1 year ago 75
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

An example of an entry:

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

I need to find all products that belong to
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.


  • Rails 4.2.4

  • Ruby 2.3.1.p112

  • SQLite3

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download