How to use after_save method to set fields on other models?

Hello,
I am having some problems using the after_save callback to update a
field on another model, could anyone give me directions?
Here is what I have:

class Model1 < ActiveRecord::Base
has_many model2

after_save :update_field_model2

def update_field_model2
self.model2.field = (SomeStuff+somevariable) * some_other_var
end
end

class Model2 < ActiveRecord::Base
belongs_to model1
end

What is the right way to update the value of the model2.field from
model1?

thank you

just fixing it*

class Model1 < ActiveRecord::Base
has_one model2

coelho wrote:

def update_field_model2
self.model2.field = (SomeStuff+somevariable) * some_other_var
end
end

class Model2 < ActiveRecord::Base
belongs_to model1
end

What is the right way to update the value of the model2.field from
model1?

The way you do it looks fine to me. If you want to persist it you will
of course have to do something like self.model2.save or
self.model2.update_attribute.

What is the issue you’re having?


Cheers,

  • Jacob A.

Yes, I wanted it to persist. It worked with model2.update_attribute, I
did not know about this method

thank you!

The way you do it looks fine to me. If you want to persist it you will
of course have to do something like self.model2.save or
self.model2.update_attribute.

What is the issue you’re having?


Cheers,

  • Jacob A.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs