tac
tac

Reputation: 209

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.

Upvotes: 1

Views: 7123

Answers (3)

dp7
dp7

Reputation: 6749

@AaditiJain answer is most preferred way of doing.

Another alternative could be using symbols instead of of ? like follows:

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

Upvotes: 8

Ilya
Ilya

Reputation: 13477

You can use question marks instead of variables and pass those variables as the second and third arguments:

Rate.where('A = ? and B = ?', x, y)

You can use the question marks in any direct SQL query, but I prefer to use standard AR query syntax with hashes (as @AaditiJain mentioned):

Rate.where(a: x, b: y)

Upvotes: 9

Aaditi Jain
Aaditi Jain

Reputation: 7027

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.

Upvotes: 3

Related Questions