Reputation: 4417
I have:
class Parent < ActiveRecord::Base
has_many :things
before_save :update_something
private
def update_something
self.update_column(:something, "something")
end
end
And
class Thing < ActiveRecord::Base
belongs_to :parent, autosave: true
end
I expect that when I save an instance of Thing
that it's Parent
should also be saved. I also expect that instance of Parent
to have it's before_save
callback called. This doesn't seem to be the case.
Any idea why this doesn't work and how I might remedy it?
Upvotes: 0
Views: 146
Reputation: 766
Referring to the docs
If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
I suggest you creating new after_save callback for Thing to update parent if you want to go Rails way.
But the OO way would be to create class that handles saving the object, such as:
class ThingUpdater
def initialize(thing)
@thing = thing
end
def call(params)
@thing.update_attributes(params)
@thing.parent.update_something
end
end
Thanks to this you will avoid callback hell - take also a look here
Upvotes: 1