Fellow Stranger Fellow Stranger - 2 years ago 69
JSON Question

Scope with argument for a json column

I have a json column -


I have specified the
attribute with
store_accessor :document, :color_code

I can successfully query all instances for the number 3:

MyModel.where("document ->> 'color_code' = '3'")

But how would I convert that query to a scope with a number argument, so I can use it more generally?

Answer Source

You can try something like this:

class MyModel
   scope :with_color, ->(color) { where("document ->> 'color_code' = '?'", color) }

and then issue the scope:

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