Hi all,
I’m trying to overwrite a setter method, but am running into some
difficulties. This is normally really easy when overwriting a setter for
a table column, but in this case it is the setter for an associated
object.
Here’s a hypothetical example:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
def user=(new_user)
self[:user] = new_user
self[:user_id] = new_user.id
# do other stuff (not relevant here)
end
end
Unfortunately self[]
only works when modifying table column values, so
self[:user] = new_user
doesn’t do anything. The only solution I have
at the moment is this…
def user=(new_user)
self[:user_id] = new_user.id
self.reload
# do other stuff
end
… which isn’t ideal, since self.reload
will have to hit the
database.
Is there any easier way to update an associated object from within a
model?
Thanks in advance,
Anthony.