情景:
[code="Ruby"]
class Model < ActiveRecord::Base
before_create :xxoo
def xxoo
other = OtherModel.create
end
end
[/code]
请问这种情况下,如果 Model#save 失败后, OtherModel会回滚吗?
也就是说 xxoo 方法是否包含在 Model#save 的事务中.
刚才理解错你的题目了... :lol:
[quote]
请问这种情况下,如果 Model#save 失败后, OtherModel会回滚吗?
也就是说 xxoo 方法是否包含在 Model#save 的事务中. [/quote]
这要看你的调用save是更新还是创建.
a.new,
a.save,
会调用before_create,同样产生错误也会回滚.
a=A.find(1)
a-----
a.save,
不会调用before_create,会调用before_update,产生错误也会回滚.
不会的.
你可以这样写.
[code="ruby"]
attr_accessor :other
before_create :xxoo
after_create :ooxx
def xxoo
@other = OtherModel.new
end
def ooxx
@other.save
end
[/code]
在一堆多,提交时,经常这样写.你可以参考下,或许对你有点用.
[code="ruby"]
validates_associated :step_materials
after_update :save_step_materials
def new_step_material_attributes=(step_material_attributes)
step_material_attributes.each do |attributes|
step_materials.build(attributes)
end
end
def existing_step_material_attributes=(step_material_attributes)
step_materials.reject(&:new_record?).each do |step_material|
attributes = step_material_attributes[step_material.id.to_s]
if attributes
step_material.attributes = attributes
else
step_materials.delete(step_material)
end
end
end
def save_step_materials
step_materials.each do |step_material|
step_material.save(false)
end
end
[/code]