has_one更新问题

发布于 2024-08-31 23:30:52 字数 151 浏览 2 评论 0原文

我有两个模型,用户和帐户。每个用户可以有一个帐户。

为用户创建帐户效果很好。我的问题是,当我尝试更新帐户时,以前的帐户 user_id 被取消,并使用 user_id 创建一个新帐户行。我不希望这种事发生。我想使用帐户更改来更新现有行。我该怎么做?

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

机场等船 2024-09-07 23:30:52

使用此代码,

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

您将构建一个新的帐户。你需要的是更新

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

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
注定孤独终老 2024-09-07 23:30:52

由于您没有提供任何代码,假设这就是您创建用户的方式

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

然后您可以通过指定 user_id 将用户与帐户关联起来

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

现在假设我们要更改帐户的状态。我们可以在rails http://api.rubyonrails.org/ 中调用更新后的方法像这样的classes/ActiveRecord/Base.html#M002270

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

我可以提供更多信息,为您提供更多帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文