views:

20

answers:

1

for

class A < ActiveRecord::Base
  has_many :bs
  has_many :cs, :through => :bs
end

class B < ActiveRecord::Base
  belongs_to :a
  belongs_to :c
end

class C < ActiveRecord::Base
  has_many :bs
end

If i bring up a rails console, and do

a = A.new
b = a.bs.build
b.c = C.new

Then i get

a.cs => []

but

a.bs[0].c => c

If a is saved, then it all works. Is this expected? why doesn't the through association work when the models only exist in memory? thanks

+1  A: 

I guess that object a has no reference to object c created. Normally it would run a query, but it won't since it is not saved to db. I think that it is created for db relations and it just doesn't check references to in-memory objects.

You can also try this:

a = A.new
a.cs.build
a.bs
=> []

but

a.cs
=> [created c object]
klew