我的关系模型看起来像:
Foo
has_many bars
我有两个记录old_cart
和new_cart
2.1.2 :014 > old_cart
=> #<Foo id: 1, user_id: nil, created_at: "2015-07-01 05:54:53", updated_at: "2015-07-01 05:54:53">
2.1.2 :015 > new_cart
=> #<Foo id: 2, user_id: 1, created_at: "2015-07-01 05:58:40", updated_at: "2015-07-01 05:58:40">
old_cart
有栏和new_cart
2.1.2 :016 > old_cart.bars
Bar Load (0.8ms) SELECT "bars".* FROM "bars" WHERE "bars"."foo_id" = $1 [["foo_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Bar id: 3, avatar: nil, created_at: "2015-07-01 05:57:47", updated_at: "2015-07-01 05:57:47", foo_id: 1>]>
2.1.2 :017 > new_cart.bars
=> #<ActiveRecord::Associations::CollectionProxy [#<Bar id: 4, avatar: nil, created_at: "2015-07-01 05:59:07", updated_at: "2015-07-01 05:59:07", foo_id: 2>]>
我希望foo_id
的{{1}}更新为new_cart.bars
,并且成功:
old_cart
2.1.2 :018 > new_cart.bars.each do |bar|
2.1.2 :019 > bar.update_attributes(foo_id: old_cart.id)
2.1.2 :020?> end
(0.5ms) BEGIN
SQL (0.8ms) UPDATE "bars" SET "created_at" = $1, "updated_at" = $2, "foo_id" = $3 WHERE "bars"."id" = $4 [["created_at", "2015-07-01 05:59:07.420889"], ["updated_at", "2015-07-01 05:59:07.420889"], ["foo_id", 1], ["id", 4]]
(13.4ms) COMMIT
=> [#<Bar id: 4, avatar: nil, created_at: "2015-07-01 05:59:07", updated_at: "2015-07-01 05:59:07", foo_id: 1>]
已被更改但关系仍未改变?
foo_id
答案 0 :(得分:1)
您需要刷新模型。使用reload
重新获取关联
new_cart.reload.bars