Megamind
Megamind

Reputation: 111

Rails using a variable on left side of where clause

I am looking to do the following:

var = 'bank_id'
id = '100'

Bank.where(var: id) or
Bank.where("? = ?", var, id)

Bank is a model. bank_id is an attribute of the model and it is taking it as a string.

Upvotes: 1

Views: 1113

Answers (3)

There's also a Arel Table approach:

Bank.where(Bank.arel_table[var].eq(id))

Upvotes: 1

Milan Köpke
Milan Köpke

Reputation: 1133

Where does accept a hash witch gets mapped to the correct SQL WHERE.

Bank.where(var: id)

is actually

Bank.where({:var => id})

So you can construct your own hash key:

Bank.where({ var.to_s => id })

Or shorter:

Bank.where(var => id)

Just to clarify: The difference actually lies in the different syntax for hash. There are basically two versions.

  1. The old "Hash-Rocket" syntax { key => value } actually accepts anything as key.
  2. The new JSON style always uses symbols als keys and thus var does not get interpreted as a variable but as the symbol :var.

Always coding has a more detailed explanation.

Upvotes: 7

JanDintel
JanDintel

Reputation: 1039

That's possible:

var = 'bank_id'
id = '100'

Bank.where("#{var} = ?", id)

But what are you using it for? Maybe there's a better way to solve the 'real' problem here.

Upvotes: 0

Related Questions