ActiveRecord对象的最佳实践,它在保存时更新另一个ActiveRecord对象

时间:2010-12-15 05:36:02

标签: ruby-on-rails activerecord callback

这是我的情况:我有两个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所有内容。任何想法

2 个答案:

答案 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.rbRails 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