Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 965
Fellow Stranger Avatar asked Nov 23 '25 11:11

Fellow Stranger


1 Answers

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)
like image 171
Малъ Скрылевъ Avatar answered Nov 26 '25 10:11

Малъ Скрылевъ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!