title: Using transaction in Ruby On Rails controller method
body: <p>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. </p>
  
  <p>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.</p>
  
  <p>in my controller:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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.</p>
  
  <p>And if one of the actions fails all database actions should roll back and give feedback about the problem.</p>
  
  <p>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.<br>
  <strong>Question</strong>: Why is this?</p>
  
  <p>So I guess this code is not the right way to implement transaction.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>What is the best/right way to handle this?</p>