itx
itx

Reputation: 1419

Update relation

I have relation model looks like :

Foo has_many bars

And I have two record old_cart and 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 have bars and new_cart too

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>]> 

I want update foo_id of new_cart.bars with old_cart, and success :

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 has been changed but relation still not change ?

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>]> 

Upvotes: 0

Views: 77

Answers (1)

Shalev Shalit
Shalev Shalit

Reputation: 1963

You need to refresh the model. use reload to refetch the association

new_cart.reload.bars

for more look here: rails - how to refresh an association after a save

Upvotes: 1

Related Questions