gpt4 book ai didi

ruby-on-rails - 做 has_many :through associations work for models that only exist in memory?

转载 作者:行者123 更新时间:2023-12-04 06:44:54 25 4
gpt4 key购买 nike

为了

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创建。通常它会运行一个查询,但它不会,因为它没有保存到 db。我认为它是为数据库关系创建的,它只是不检查对内存中对象的引用。

你也可以试试这个:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com