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

标签 ruby-on-rails activerecord associations

对于

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/

相关文章:

ruby-on-rails - 无法创建新的 Spree 应用程序 : "undefined method ` raise_in_transactional_callbacks ='"

ruby-on-rails-4 - 使用 Rails ar-octopus gem 执行事务

ruby-on-rails - Rails has_many :through and Setting Property on Join model

c# - 在 WPF 中打开关联文件,例如 'notepad++ tab features'

ruby-on-rails - Ubuntu Nginx、Rails 和 Thin

ruby-on-rails - 需要管理员批准的设计和用户注册

sql - 在 Rails 3.1 上使用子查询作为表

ruby-on-rails - 如何在 rspec 中 stub HTTP POST 请求?

ruby-on-rails - 如何测试 Rails 3 中的路由错误?

mysql - Doctrine 选择 innerJoined 实体或没有关联的实体