ActiveRecord: Minor saving problem


#1

This is probably a very stupid error on my side, but I am doing my
first steps now and I don’t see what is wrong.

I have companies and I have users. A user can create a company. When
the user does he’s automatically a member of the company. A company
should be able to have multiple users off course so every member of a
company can add other users who don’t have a company yet. This last
step is what I am trying to implement now.

The function in the controller:
def invite
@invite_user=User.find(:first, :conditions => [“company_id = 0 AND
id = ?”, params[:id]])
if @invite_user
@invite_user.company_id = @session[:user].company_id
@invite_user.save
flash[:notice] = “User #{@invite_user.real_name} was
successfully added to your company #{@invite_user.company_id}”
else
flash[:notice] = “Sorry, I couldn’t add this user to your company”
end
redirect_to :action => ‘no_company’
end

The flash message does tell me I have the right user in @invite_user
and the displayed company_id is correct too, but the company_id is not
saved in the database.

Can anyone tell me what I am doing wrong here?

Regards,
Wijnand


#2

Ok, never mind.
Following code does work ok:

def invite
@invite_user=User.find(:first, :conditions => [“company_id = 0 AND
id = ?”, params[:id]])
if @invite_user.update_attribute(:company_id,
@session[:user].company_id)
flash[:notice] = “User #{@invite_user.real_name} was
successfully added to your company #{@invite_user.company_id}”
else
flash[:notice] = “Sorry, I couldn’t add this user to your company”
end
redirect_to :action => ‘no_company’
end