0

I have 2 Ruby on Rails model classes A and B which are dependent and I want to save one when I save the other.

My current solution is to use a temporary attribute like on How to avoid ActiveRecord model double saving? But is there a better way ?

class A < ActiveRecord::Base  
  has_many :b

  attr_writer :save_b_values

  def save_b_values
    return @save_b_values if defined? @save_b_values
    true
  end

  before_save do
    save_b_values = false

    if save_b_values
      b.each do |bi|
        bi.save!
      end
    end
  end

  after_save do
    save_b_values = true
  end
end

class B < ActiveRecord::Base
  belongs_to :a, autosave: true
end
Community
  • 1
  • 1
nicolasleger
  • 1
  • 1
  • 1

0 Answers0