Posts Tagged ‘sql’

ActiveRecord and Transactions!

Wednesday, October 29th, 2008

If you ever have to do multiple actions with activerecord, you should group it into a transaction like so:

Post.transaction do
  posts.each do |post|
    post = Post.new(:body=>'Whatever')
    post.save!
  end
end

This will rollback too if the save fails.

Bulk update using ActiveRecord without SQL!

Thursday, October 23rd, 2008

Here is a cool way you can update columns in a table without writing any SQL using ActiveRecord. Suppose you have a form with checkboxes that are for deleting posts for the ones that are checked:

<input type="checkbox" name="posts[]" value="<%= post.id %>">

Now you can update this in the method of your controller that this form posts to:

Post.update_all({:removed=>true}, {:id=>params[:posts]})

ActiveRecord will take of the fact that you want to update 1 record or multiple!