views:

28

answers:

2

I have two models, User and Account. Each user may have one account.

Creating an account for a user works fine. My problem is that when I try to update the account, the previous accounts user_id is nullified and a new account row is created with the user_id. I do not want this happening. I want to update the existing row with the changes to account. How do I do this?

Thanks.

+1  A: 

Since you didn't provide any code lets say this is how you create a user

user = User.create(:name => "bob")

Then you can associate the user with an account by specifying the user_id

account = Account.create(:user_id =>user.id, :status => "not activated")

Now lets say we want to to change the status of the account. We can call the updated method in rails http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002270 like this:

Account.update( account.id, :status => "activated")

I can be more helpful with more info.

ThinkBohemian
+1  A: 

With this code

@account = @user.account.build(params[:account])
if @account.save 
   #... 
else 
   #...
end 

you're building a new account. What you need is to update

if @account.update_attributes(params[:account])
   #...
else
   #...
end
j.
update_attributes is more elegant than update in this situation...good call
ThinkBohemian
apparently i lost my "accepted solution" for this opinion :( bye bye points
ThinkBohemian
hahah it happens =P
j.