Blog Entries tagged "activerecord"


TIL: Pass in an ActiveRecord Object to a where string

I’m surprised I didn’t already know this, but if you have an ActiveRecord where statement that references an id column, you can just pass in an object and it will pass in the object’s id, not the string representation of the object.

company = Company.find(1)

User.where("users.company_id = ?", company)
# is equal to
User.where("users.company_id = ?", company.id)

So when you create named scopes, you don’t have to do the song-and-dance where you check to see if the object is a model or an integer, as shown below.

scope :by_company, lambda { |company|
 ...

Read More...