I want to create some DRY code by inputting a variable key in the where clause in AR
if I have the field as :email and val as '[email protected]'
how would I write it in Ruby 2 syntax?
with previous syntax I could write
Model.where(field => val)
which would be Model.where(:email => '[email protected]')
in Ruby 2 the where can be written as Model.where(email: '[email protected]')
but how would I use the field variable in this situation?
something: valueis just a syntax sugar for:something => value.variable => val. But if you specify the symbol directly you can do bothsymbol: valand:symbol => val. Now, there are now named arguments in functions in Ruby 2 as well (robots.thoughtbot.com/ruby-2-keyword-arguments), but this is not the case.where(:email => "...")is just yet another syntactic sugar on top ofwhere({:email => "..."}). You can drop{}around hash, if it's the last argument. See stackoverflow.com/questions/16576477/….Model.where({field => val}).