-
-
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 |
You certainly can do the setting from model_a. Both of the patterns suggested will work.
I prefer the latter because I think it's a more "proper" place for the responsibility of setting that value to lie. But that's more of a "code design" conversation than just a question of what will work.
I agree with you, I would rather have one place to set these value instead.
ok, i might have something else going on in the code preventing what I want to do.
i will spin up a fresh rails project and see if i still have the same problem.
thanks for your help!
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
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.
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.
OIC. have
model_b
get its value frommodel_a
... I have this working.I was wondering why I can just do all this setting right from
model_a
(these are tightly linked models)