Search code examples
ruby-on-railssqliterails-console

rails: How to find entries with empty arrays


I've got an issue finding empty arrays in a SQLITE table.

I serialized the product_category param, which works well for saving arrays into my DB, as follows:

serialize :product_category, Array

The following is query to find all empty arrays for this param, but its giving me an nil error:

Product.where(product_category: []).first

How do i find Products where the product_category has no values in its array?

I tried using {} instead of [] as suggested in a similar POSTGRESS related question.

Does anyone know the right way?


Solution

  • I have tried this on mysql, this works for me, please try.

    #product.rb
    serialize :product_category, Array
    
    #rails console
    >> product = Product.new
    >> product.product_category = []
    >> product.save
    >> Product.where("product_categoty = '[]'") #It returns the last record that we have just created.
    

    Hope this help!