Showing posts with label active. Show all posts
Showing posts with label active. Show all posts

Wednesday, March 18, 2015

Find multiple records with ActiveRecord's Model.find

This is something cool that it took me over a year of coding in Ruby to find out. If I have a comma separated list or an array of IDs, I can find all of the records in one call:

  Model.find(ids)

Caveat: This will give the objects back in an array. However, if you want to run ActiveRecord methods on this, better to use this:

  Class.where(id: ids)

Then, you can chain methods like so:

  Class.where(id: ids).update_all(updated_at: Time.now)

Be careful! update_all does NOT run validations. But it is incredibly useful for updating several records without instantiating all of the objects. This is a straight sequel query, hence no callbacks.