# AR Callbacks and associations

**URL:** <https://www.ruby-forum.com/t/ar-callbacks-and-associations/124243>\
**Category:** Rails\
**Created:** [December 27, 2007, 12:51am UTC](https://www.ruby-forum.com/t/ar-callbacks-and-associations/124243 "2007-12-27T00:51:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [December 27, 2007, 12:51am UTC](https://www.ruby-forum.com/t/ar-callbacks-and-associations/124243/1 "2007-12-27T00:51:53Z")

</div>

Hello,

I have this model in Rails 2.0:  
class Contact \< ActiveRecord::Base  
before\_save :update\_contact\_user

belongs\_to :user

belongs\_to :contact\_user, :class\_name=\>‘User’,  
:foreign\_key=\>‘contact\_user\_id’

validates\_presence\_of :user, :fullname, :email  
validates\_as\_email :email  
validate\_phone :home\_tel, :mobile\_tel, :office\_tel

private  
def update\_contact\_user  
#check if some user matches the email entered  
cuser = User.find :first, :conditions=\>[“email = ?”, email]  
contact\_user = cuser if cuser  
end

end

The callback is called correctly and finds a user, but for some reason  
the association is not updated. If I do the same code in the calling  
method (just before I call ‘save’) then it is working. Any guess? Am I  
missing something?

Thank you,  
Julien.

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [December 27, 2007, 2:41am UTC](https://www.ruby-forum.com/t/ar-callbacks-and-associations/124243/2 "2007-12-27T02:41:34Z")

</div>

Julien :

> validate\_phone :home\_tel, :mobile\_tel, :office\_tel  
> The callback is called correctly and finds a user, but for some reason  
> the association is not updated. If I do the same code in the calling  
> method (just before I call ‘save’) then it is working. Any guess? Am I  
> missing something?

in update\_contact\_user method, contact\_user is a local variable.

Try : self.contact\_user = cuser if cuser

– Jean-François.

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [December 27, 2007, 3:27am UTC](https://www.ruby-forum.com/t/ar-callbacks-and-associations/124243/3 "2007-12-27T03:27:45Z")

</div>

Duh.

Guess you should not code after Christmas 🙂

Thanks,  
Julien.

On Dec 26, 8:40 pm, “Jean-François Trân” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
