Overwriting setters for associated objects

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.

an idea would be to use alias_method

so in your example

alias_method ‘ar_user=’, ‘user=’
def user=(new_user)
# some custom logic here
ar_user = new_user
end

hope this helps.