Fellow Stranger Fellow Stranger - 6 months ago 11
JSON Question

Scope with argument for a json column

I have a json column -

document
.

I have specified the
color_code
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

You can try something like this:

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

and then issue the scope:

MyModel.with_color(3)