gpt4 book ai didi

ruby-on-rails - 嵌套属性 update_attributes 使用插入而不是更新

转载 作者:行者123 更新时间:2023-12-03 09:36:04 25 4
gpt4 key购买 nike

我有一个用户和嵌套的配置文件类,如下所示:

class User < ActiveRecord::Base
has_one :profile
attr_accessible :profile_attributes
accepts_nested_attributes_for :profile
end

class Profile < ActiveRecord::Base
belongs_to :user
attr_accessible :name
end

user = User.find(1)
user.profile.id # => 1
user.update_attributes(profile_attributes: {name: 'some name'})
user.profile.id # => 2

我不明白为什么 rails 会丢弃旧的配置文件并创建一个新的配置文件。

使用
user.profile.update_attributes({name: 'some name'})

只是按预期更新当前配置文件。
但在那种情况下,我没有利用 accepts_nested_attributes_for

有谁知道为什么更新会这样?我不希望以未连接到任何用户的配置文件行数据库结束。

最佳答案

对于在 Rails 4 中遇到相同问题的每个人: fields_for 已经为您的嵌套表单添加了 id 但您必须允许 :id 参数。我只允许一个 :object_name_id 参数,因为这不会引发任何错误,所以我花了一些时间直到我在服务器日志中看到这个。希望这有助于有人在这方面浪费的时间比我少 :)

关于ruby-on-rails - 嵌套属性 update_attributes 使用插入而不是更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9944065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com