Search code examples
ruby-on-railsrubyruby-on-rails-4

How do I use a variable in `where` clause in Rails?


How do I use a variable in the where function ?

I have a Rate model with two fields A and B (both integers) and this works :

Rate.where('A = 1 and B = 2')

How do I pass a variable that I got in params hash ?

x = params[:x]
y = params[:y]
Rate.where('A = x and B = y')

This doesn't work and returns an error.


Solution

  • Why not a simple: Rate.where(a: params[:x], b: params[:y])

    It should work fine. It will run a query like below in the database:

    SELECT rates.* FROM rates WHERE rates.a = 'param_x_value' 
      AND rates.b = 'params_y_value'
    

    Use Rails available syntax as much as possible, and avoid string literal.