Forum: Ruby on Rails Overwriting setters for associated objects

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community 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
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.
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
  end

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