簡體   English   中英

為什么不能以1:1關聯更新對象的外鍵?

[英]Why can I not update the foreign key of an object in a 1:1 association?

我有兩個模型,用戶和配置文件。 用戶has_one配置文件和配置文件belongs_to用戶。 相應地,Profile模型具有user_id屬性。

該協會的工作:

p = Profile.first
=> #<Profile id: 1, name: "Jack", ... , user_id: 1>
u = User.first
=> #<User id: 1, email: "jack@example.com", ... >
u.profile.id
=> 1
p.user.id
=> 1
p.user == u
=> true
u.profile == p
=> true

我可以直接在個人資料上設置user_id字段:

p.user_id = 2
=> 2
p.save!
=> true
p.user_id
=> 2

但是為什么不能這樣設置user_id

u.profile.user_id = 2
=> 2
u.profile.save!
=> 2
u.profile.user_id
=> 1

您必須刷新u.profile對象。 嘗試這個:

u.profile.user_id = 2
=> 2
u.profile.save!
=> 2
u.profile.reload.user_id
=> 2

這是因為original配置文件對象仍加載在u內存中。

希望這個幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM