Kalyan Maddu
Kalyan Maddu

Reputation: 4173

has_one update problem

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.

Upvotes: 4

Views: 1705

Answers (2)

Ju Nogueira
Ju Nogueira

Reputation: 8461

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

Upvotes: 4

Schneems
Schneems

Reputation: 15898

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.

Upvotes: 1

Related Questions