ActiveRecord :: Associations :: CollectionProxy在保存和重新加载之前为空

时间:2014-08-22 00:18:55

标签: ruby-on-rails activerecord rails-activerecord

我很好奇为什么在我的对象保存并重新加载之后才会填充has_many :through关联。似乎所有的数据都应该用于构建连接。

架构:

ActiveRecord::Schema.define(version: 20140821223311) do
  create_table "cats", force: true do |t|
    t.string   "name"
    t.integer  "human_id"
  end
  create_table "houses", force: true do |t|
    t.string   "address"
  end
  create_table "humen", force: true do |t|
    t.string   "name"
    t.integer  "house_id"
  end
end

型号:

class Cat < ActiveRecord::Base
  belongs_to :human, inverse_of: :cats
  has_one :house, through: :human
  has_many(
    :siblings,
    through: :house,
    source: :cats
  )
end
class Human < ActiveRecord::Base
  has_many :cats, inverse_of: :human
  belongs_to :house, inverse_of: :humans
end
class House < ActiveRecord::Base
  has_many :humans, inverse_of: :house
  has_many :cats, through: :humans
end

我在数据库中保存了House和Human的实例。种子文件如下所示:

h = House.create(address: "123 Main")
Human.create(house_id: h.id, name: "stu")

我一直在测试:

c = Cat.new(human_id: 1, name: "something awesome")
p c.siblings # => #<ActiveRecord::Associations::CollectionProxy []>
c.save
p c.siblings # => #<ActiveRecord::Associations::CollectionProxy []>
c.reload
p c.siblings # => #<ActiveRecord::Associations::CollectionProxy [#<Cat id: 2, name: "gizmo", created_at: "2014-08-21 22:37:07", updated_at: "2014-08-21 22:37:07", human_id: 1>]>

对此的任何帮助将不胜感激:)

这是一个github回购,如果你想玩它: https://github.com/w1zeman1p/association_wat

1 个答案:

答案 0 :(得分:0)

似乎CollectionProxy有点太懒了。如果你这样做:

c = Cat.new(human_id: 1, name: "something awesome")
c.save
c.siblings

你得到了你所期望的。

因此,在保存cat之前,可能会在第一次调用.siblings时缓存CollectionProxy。