Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating several records at once in rails

In a rails 2 app I'm building, I have a need to update a collection of records with specific attributes. I have a named scope to find the collection, but I have to iterate over each record to update the attributes. Instead of making one query to update several thousand records, I'll have to make several thousand queries.

What I've found so far is something like Model.find_by_sql("UPDATE products ...)

This feels really junior, but I've googled and looked around SO and haven't found my answer.

For clarity, what I have is:

ps = Product.last_day_of_freshness ps.each { |p| p.update_attributes(:stale => true) } 

What I want is:

Product.last_day_of_freshness.update_attributes(:stale => true) 
like image 738
brycemcd Avatar asked Mar 22 '11 16:03

brycemcd


People also ask

What is Active Record in rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What's the purpose of Active Record?

Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

Does update call Save rails?

update!(attributes) LinkUpdates its receiver just like update but calls save! instead of save, so an exception is raised if the record is invalid. Also aliased as: update_attributes!


1 Answers

It sounds like you are looking for ActiveRecord::Base.update_all - from the documentation:

Updates all records with details given if they match a set of conditions supplied, limits and order can also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations.

Product.last_day_of_freshness.update_all(:stale => true) 

Actually, since this is rails 2.x (You didn't specify) - the named_scope chaining may not work, you might need to pass the conditions for your named scope as the second parameter to update_all instead of chaining it onto the end of the Product scope.

like image 118
Brett Bender Avatar answered Sep 25 '22 01:09

Brett Bender