Forum: Ruby on Rails belongs_to trigger on update?

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.
Ed W. (Guest)
on 2007-05-16 22:07
(Received via mailing list)
This may be a rails bug, but I can't figure out how to do attribute
overrides for the attribute created for a belongs_to relationship


I have a simple relationship:
    User belongs_to Domain

User has a property email_address which I want to update if Domain is
ever changed

I tried in User

def domain=(new_domain)
  super
end

but now the ability to assign new domains is totally broken and no
longer works (simply nothing happens)...

I suspect that this needs some magic reflection hacking, but can someone
set me on the right path to figure out how to work around it.  Basically
I want to just intercept the update call and run some custom code to
update the User model.

Grateful for some ideas

Ed W
Mark Reginald J. (Guest)
on 2007-05-17 00:24
(Received via mailing list)
Ed W wrote:
> I tried in User
> I want to just intercept the update call and run some custom code to
> update the User model.

Yes, you can't use super because AR defines the domain= method on
the User class itself.

Instead use:

   def domain_with_email_update=(new_domain)
     self.email_address = blah(new_domain)
     self.domain_without_email_update = new_domain
   end
   alias_method_chain :domain=, :email_update

Now user.domain = ...  will also do an email update, but you can
use user.domain_without_email_update = ... for cases where you
don't want the email address updated.


--
We develop, watch us RoR, in numbers too big to ignore.
This topic is locked and can not be replied to.