为什么我不能以1:1关联更新对象的外键?

时间:2015-10-01 19:29:49

标签: mysql ruby-on-rails

我有两个型号,User和Profile。 用户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

1 个答案:

答案 0 :(得分:1)

您必须刷新u.profile个对象。试试这个:

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

这是因为original配置文件对象仍然加载到u的内存中。

希望这有帮助:)