AR Callbacks and associations

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.

Julien :

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?

in update_contact_user method, contact_user is a local variable.

Try : self.contact_user = cuser if cuser

   -- Jean-François.

Duh.

Guess you should not code after Christmas :slight_smile:

Thanks,
Julien.