问题描述
我有一个用户和嵌套的概要文件类,如下所示:
I have a user and nested profile class as follows:
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会丢弃旧的配置文件并创建新的配置文件.
I don't understand why rails is throwing away the old profile and creating a new one.
使用
user.profile.update_attributes({name: 'some name'})
仅按预期更新当前配置文件.但是在那种情况下,我不会利用accepts_nested_attributes_for
just updates the current profile as expected.But in that case I'm not taking advantage of accepts_nested_attributes_for
有人知道为什么以这种方式进行更新吗?我宁愿不要以未连接任何用户的配置文件行数据库结束.
Does anyone know why the update happens this way? I'd prefer not to end up with a database of profile rows not connected to any user.
推荐答案
我通过添加update_only
选项解决了这个问题:
I solved this problem by adding the update_only
option:
accepts_nested_attributes_for :profile, update_only: true
现在,仅当一个新的配置文件不存在时,才创建它.
Now a new profile is only created if one does not already exist.
这篇关于嵌套属性update_attributes使用插入而不是更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!