我有一個用戶和嵌套檔類別如下:嵌套屬性用途的update_attributes插入,而不是更新
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'})
剛剛更新如預期的當前配置文件。 但在這種情況下,我沒有利用accepting_nested_attributes_for
有誰知道爲什麼更新發生這種方式?我不想最終沒有連接到任何用戶的配置文件行數據庫。
可能你可以嘗試'user.update_attributes(profile_attributes:{:id => user.profile.id,:name:'some name'})' – 2012-03-30 13:57:48