Forum: Ruby on Rails Overwriting setters for associated objects

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Anthony (Guest)
on 2006-05-07 21:41
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

Here's a hypothetical example:

  class User < ActiveRecord::Base
    has_many :posts

  class Post < ActiveRecord::Base
    belongs_to :user

    def user=(new_user)
      self[:user] = new_user
      self[:user_id] =

      # do other stuff (not relevant here)

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] =

    # do other stuff

... which isn't ideal, since `self.reload` will have to hit the

Is there any easier way to update an associated object from within a

Thanks in advance,
cyx (Guest)
on 2006-05-07 22:18
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

hope this helps.
This topic is locked and can not be replied to.