Rails控制器操作是否隐式定义了事务边界?

时间:2012-07-03 02:15:05

标签: ruby-on-rails ruby 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

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

1 个答案:

答案 0 :(得分:4)

简要回答:您需要在事务块中明确地包装代码。基本上,当您想要执行一组SQL语句时,必须使用事务,以保持参照完整性。

Something.transaction do 
  @something.save
  thing.save
end

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