Problem with has_one problem

I have two models: User and Account. Each user can have one account.

Creating an account for the user works great. My problem is that when I try to update my account, the previous user_id accounts are reset and a new account line is created using user_id. I do not want this to happen. I want to update an existing row with account changes. How can I do it?

Thanks.

+4
source share
2 answers

Using this code

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

you create a new account . You need to update

 if @account.update_attributes(params[:account]) #... else #... end 
+3
source

Since you did not enter any code, say that this is how you create the user

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

You can then associate the user with the account by specifying user_id

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

Now let's say we want to change the status of the account. We can call the updated method in rails http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002270 as follows:

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

I can be more helpful with more information.

+1
source

Source: https://habr.com/ru/post/1309335/


All Articles