Using transaction in Ruby On Rails controller method

MDekker picture MDekker · Jun 11, 2015 · Viewed 9.1k times · Source

I love Ruby On Rails and every day I am learning and improving my skills. Currently I am working on an application that is used by several clients and I want to refactor my code so I can feel confident about the quality of my code.

I am struggling with how I should implement exception handling and make use of Transactions. I have a controller that has to create and update three objects.To simplify my situation.

in my controller:

def update
  @user.change_value_x  #(1) effects Model 'User'
  if condition == y 
    @user.create_coupon #(2) effects Model 'Coupon' via Model 'User' 
  end
  create_a_history_item #(3) effect Model 'History' 
end

The first (1) and the second method (2) are located in the User Model and the third method (3) is also used by other controllers and is located in a Module in the /lib directory. All methods are updating/saving/creating database items.

And if one of the actions fails all database actions should roll back and give feedback about the problem.

I know that 'transaction' is a good solution for this and I have also red, in different posts, that a transaction should not be used in a controller.
Question: Why is this?

So I guess this code is not the right way to implement transaction.

def update
  ActiveRecord::Base.transaction do
    @user.change_value_x  #(1) effects Model 'User'
    if condition == y 
      @user.create_coupon #(2) effects Model 'Coupon' via Model 'User' 
    end
    create_a_history_item #(3) effect Model 'History'
  end
  rescue
  #some code that gives feedback to user about the problem
end

What is the best/right way to handle this?

Answer

Julien Portalier picture Julien Portalier · Jun 11, 2015

Transactions should be kept at the model level as much as possible, since they are related to the model, not to the logic. A transaction in a controller is like a SQL request in a controller: it feels out of place.

That being said, there is nothing wrong with your solution, but maybe having methods on your models (or a service layer) would help keep things clean in your controller? Methods like User#update_x_and_create_coupon and User#update_x_and_create_history_item for example.