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|
    company_id = company.is_a?(Company) ? company.id : company
    where( "users.company_id = ?", company_id )
# You wouldn't actually want to use a string in this example.
# Try to only use strings in very complex scopes and queries.