Skip to content

Instantly share code, notes, and snippets.

@a-leung
Last active January 8, 2016 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-leung/4b9df65ed98f82e1baac to your computer and use it in GitHub Desktop.
Save a-leung/4b9df65ed98f82e1baac to your computer and use it in GitHub Desktop.
has_many model_B
before_save set_model_b_attributes
def set_model_b_attributes
self.bs.each do |b|
b.value = self.value
end
end
belongs_to model_A, inverse_of: model_B
@brycesenz
Copy link

class ModelA < ActiveRecord::Base
  has_many model_B
  before_save set_model_b_attributes

  def set_model_b_attributes
    self.bs.each do |b|
      b.update_value(self.value)
    end
  end
end

class ModelB < ActiveRecord::Base
  belongs_to model_A

  def update_value(new_val)
    self.value = new_val
    self.save!
  end
end

@a-leung
Copy link
Author

a-leung commented Jan 7, 2016

I will try that. The app has a lot more going on so I will try a few things in a fresh project instead first.

@a-leung
Copy link
Author

a-leung commented Jan 8, 2016

@brycesenz

Got this working! (model_a setting model_b.attribute)

I think I was trying to write to model_b too late in the whole save process (or after model_b validated and basically frozen for changes).

Thanks for working through this with me. It definitely helped to know that this was not 'impossible' to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment