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?
Transactions in ActiveRecord Every database operation that happens inside that block will be sent to the database as a transaction. If any kind of unhandled error happens inside the block, the transaction will be aborted, and no changes will be made to the DB.
As the two answers said, you should not be calling controller methods from your models. It is not recommended.
Rails transactions are a way to ensure that a set of database operations will only occur if all of them succeed. Otherwise they will rollback to the previous state of data.
Before Filters ADVERTISEMENT. ADVERTISEMENT. Rails before filters are executed before the code in action controller is executed. The before filters are defined at the top of a controller class that calls them. To set it up, you need to call before_filter method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With