Given the following code:
def create
@something = Something.new(params[:something])
thing = @something.thing # another model
# modification of attributes on both 'something' and 'thing' omitted
# do I need to wrap it inside a transaction block?
@something.save
thing.save
end
Would create method be wrapped in ActiveRecord transaction implicitly, or would I need to wrap it into the transaction block? If I do need to wrap it, would this be the best approach?
The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.
Rails Controllers are just Ruby Classes, storing a series of actions. The "actions" (instance methods) work on passed data ( params ) to create objects that can either be passed to the model, or used inside other methods.
Abstract Controller Callbacks Abstract Controller provides hooks during the life cycle of a controller action. Callbacks allow you to trigger logic during this cycle. Available callbacks are: after_action. append_after_action.
When writing controllers in Ruby on rails, using before_action (used to be called before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It's what you want to use to "prepare" the data necessary before the action executes.
Brief answer : You need to explicitly wrap your code in a transaction block. Basically you must use transactions when you want to execute a group of SQL statements, to maintain referential integrity.
Something.transaction do
@something.save
thing.save
end
Further reading: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html
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