0
votes

here's my situation: I have two ActiveRecord models:

class SomeAction < ActiveRecord::Base
  has_one :moderation
end

class Moderation < ActiveRecord::Base
  belongs_to :some_action
end

I would like Moderation to update SomeAction's status attribute to "complete" when I save the moderation associated with it. I would like the moderation to NOT save if for some reason the update to SomeAction was unsuccessful. I know I should be doing this in the before_save callback, however returning false (after realizing that the SomeAction record was not updatable) will not ROLLBACK everything. Any ide

2

2 Answers

2
votes

You want to use :autosave which will automatically validate the associated model fo ryou.

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

More info in activerecord/lib/active_record/autosave_association.rb, or the Rails documentation

1
votes

Make sure your table support transactions (i.e. MySQL InnoDB), then do the following:

class Moderation < ActiveRecord::Base
  belongs_to :some_action

  def do_save
    transaction do
      some_action.status = 'complete'
      some_action.save!
      save!
    end
  end

end