2015-07-01 90 views
0

我有關係模型的樣子:更新關係

Foo的has_many bars

而且我有兩個記錄old_cartnew_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>]> 

我想更新old_cartnew_cart.barsfoo_id,併成功:

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已經改變,但仍然關係不會改變?

2.1.2 :021 > old_cart.bars 
=> #<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 :022 > 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: 1>]> 

回答