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事务中,还是需要将其包装到事务块中?如果我确实需要包装它,这是最好的方法吗?
简短的回答:您需要将代码显式包装在事务块中。基本上,当您想要执行一组 SQL 语句时,必须使用事务来维护引用完整性。
Something.transaction do
@something.save
thing.save
end
Run Code Online (Sandbox Code Playgroud)
进一步阅读:http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html
| 归档时间: |
|
| 查看次数: |
946 次 |
| 最近记录: |