Thursday, December 3, 2009

Ruby on Rails Techniques

Group Operations in a Transaction

ActiveRecord is the handy persistence engine that allows you to do many cool things with data and logic. One of the really handy things that ActiveRecord allows you to do is to group multiple inserts in a single transaction.

Instead of

my_collection.each do |q|

Quote.create({:phrase => q})

end

Use:

Quote.transaction do

my_collection.each do |q|

Quote.create({:phrase => q})

end

end

or for rolling back the whole transaction if any insert fails, use:

Quote.transaction do

my_collection.each do |q|

quote = Quote.new({:phrase => q})

quote.save!

end

end

No comments:

Post a Comment