Reputation: 111
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
Reputation: 11
There's also a Arel Table approach:
Bank.where(Bank.arel_table[var].eq(id))
Upvotes: 1
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.
Always coding has a more detailed explanation.
Upvotes: 7
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