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

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.


Solution

  • 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.