Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I query for models with empty serialized fields?

When I have a model like,

class Order < ActiveRecord::Base
    serialize :shipping_lines

    ...
end

How can I find all records where shipping_lines is empty? If I do,

Order.select(order.shipping_lines).limit(5)

I get,

=> [#<Order id: nil, shipping_lines: [#<ShippingLine:0x007f8c5d10ced0>]>,
 #<Order id: nil, shipping_lines: [#<ShippingLine:0x007f8c6ef84718>]>,
 #<Order id: nil, shipping_lines: []>,
 #<Order id: nil, shipping_lines: []>,
 #<Order id: nil, shipping_lines: []>

But then the query Order.where(shipping_lines: []) yields [] and calling to_sql on the same query yields => "SELECT \"orders\".* FROM \"orders\" WHERE 1=0"

How should I go about selecting just the orders that have the default value, or an empty array, for their shipping lines?

like image 587
Ziggy Avatar asked Oct 23 '14 19:10

Ziggy


1 Answers

The only way I found while working on similar issue in my project is to directly cast empty array to YAML like this:

Order.where(shipping_lines: [].to_yaml)

Looks like a dirty hack but at least it solves the problem.

like image 59
raeno Avatar answered Sep 18 '22 03:09

raeno