Rails控制器动作是否隐含地定义了事务性债券?

ale*_*333 6 ruby ruby-on-rails ruby-on-rails-3

给出以下代码:

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
Run Code Online (Sandbox Code Playgroud)

将create方法隐式包装在ActiveRecord事务中,还是需要将其包装到事务块中?如果我确实需要包装它,这是最好的方法吗?

Ana*_*hah 4

简短的回答:您需要将代码显式包装在事务块中。基本上,当您想要执行一组 SQL 语句时,必须使用事务来维护引用完整性。

Something.transaction do 
  @something.save
  thing.save
end
Run Code Online (Sandbox Code Playgroud)

进一步阅读:http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html