Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rails controller actions define transactional bondaries implicitly?

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?

like image 414
alexs333 Avatar asked Jul 03 '12 02:07

alexs333


People also ask

What does controller do in Rails?

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.

What are actions in rails?

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.

What is controller callback in rails?

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.

What does before action do in Rails?

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.


1 Answers

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

like image 80
Anand Shah Avatar answered Sep 27 '22 21:09

Anand Shah