简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM