这是我的情况:我有两个ActiveRecord模型:
class SomeAction < ActiveRecord::Base
has_one :moderation
end
class Moderation < ActiveRecord::Base
belongs_to :some_action
end
当我保存与之关联的审核时,我希望审核将SomeAction的状态属性更新为“完成”。如果由于某种原因对SomeAction的更新失败,我希望审核不要保存。我知道我应该在before_save回调中执行此操作,但是返回false(在意识到SomeAction记录不可更新之后)将不会ROLLBACK所有内容。任何想法
答案 0 :(得分:2)
您想要使用:自动保存,它会自动为您验证相关的模型。
class SomeAction < ActiveRecord::Base
has_one :moderation
end
class Moderation < ActiveRecord::Base
belongs_to :some_action, :autosave => true
before_validation do |moderation|
moderation.some_action.complete # Changes state
end
# autosave kicks in and validates the associated record
# If validation for some_action fails, the error messages will be pulled up in Moderation
end
activerecord/lib/active_record/autosave_association.rb或Rails documentation
中的更多信息答案 1 :(得分:1)
确保您的表支持事务(即MySQL InnoDB),然后执行以下操作:
class Moderation < ActiveRecord::Base
belongs_to :some_action
def do_save
transaction do
some_action.status = 'complete'
some_action.save!
save!
end
end
end