Belongs_to trigger on update?

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

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs