我有两个型号,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
答案 0 :(得分:1)
您必须刷新u.profile
个对象。试试这个:
u.profile.user_id = 2
=> 2
u.profile.save!
=> 2
u.profile.reload.user_id
=> 2
这是因为original
配置文件对象仍然加载到u
的内存中。
希望这有帮助:)