对于
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
如果我打开 Rails 控制台,然后执行
a = A.new
b = a.bs.build
b.c = C.new
然后我明白了
a.cs => []
但是
a.bs[0].c => c
如果 a 已保存,则一切正常。这是预期的吗?当模型只存在于内存中时,为什么直通关联不起作用?谢谢
最佳答案
我猜对象a
没有对创建的对象c
的引用。通常它会运行查询,但它不会,因为它没有保存到数据库。我认为它是为数据库关系创建的,它只是不检查对内存中对象的引用。
您也可以尝试这个:
a = A.new
a.cs.build
a.bs
=> []
但是
a.cs
=> [created c object]
关于ruby-on-rails - 做 has_many :through associations work for models that only exist in memory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3842666/