2015-10-01 105 views
1

我有兩個模型,用戶和配置文件。 用戶has_one配置文件和配置文件belongs_to用戶。 相應地,配置文件模型具有user_id屬性。爲什麼我不能更新1:1關聯中的對象的外鍵?

該協會的工作原理:

p = Profile.first 
=> #<Profile id: 1, name: "Jack", ... , user_id: 1> 
u = User.first 
=> #<User id: 1, email: "[email protected]", ... > 
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 

回答

1

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

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

這是因爲original配置文件對象在u仍裝上內存。

希望這個幫助:)

相關問題