Understand Transaction in Rails

Reading time ~1 minute

What transaction do?

Before beginning , let’s read some code

  # in /controllers/queue_items_controller.rb
  def update_queue
    begin
      update_queue_items
      normalize_queue_items_positions
    rescue ActiveRecord::RecordInvalid
      flash[:error] = "Invalid position numbers"
    end
    redirect_to my_queue_path
  end

  private

  def update_queue_items
    ActiveRecord::Base.transaction do
      params[:queue_items].each do |queue_item_data|
        queue_item = QueueItem.find(queue_item_data["id"])
        queue_item.update_attributes!(position: queue_item_data["position"]) if queue_item.user == current_user
      end
    end
  end

Could you figure out what Transactions do by reading the code above?

Let’s read the Rails documentation about Transactions:

Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action.

So you have to deal multiple things with model(s), and you want to make sure that all of the things must be done successful then saving to the database. Just like you do the bank account: You deposit some money, sent to another account. Both two actions must be successful at the same time.

Exception handling and rolling back

If you want to use ActiveRecord::Base.transaction , you have to use begin...rescue statement to catch the rollback error. So in the code above, we use update_attributes! with bang to raise ActiveRecord::RecordInvalid~(this is raise by ~save!, create! in ActiveRecord, reading the documentation for more)

That’s what the transactions do.

some take away

  • use in the controller
  • try to catch the error
  • use in multiple model manipulation in one action
  • reading recommendation: Transactions in Rails

to_param in Ruby on Rails

If I want a custom slug=======================I walk through this cutstom slug.1. create migration `add_slug` to add a column inside the...… Continue reading

What is ORM in Rails mean?

Published on July 14, 2017