有嵌套关系的model has_one

class Book < ActiveRecord::Base
 has_one :distributor
end

class Distributor < ActiveRecord::Base
 belongs_to :book
 has_many :agents
end

class Agent < ActiveRecord::Base
 belongs_to :distributor
 has_many :shops
end

class Shop < ActiveRecord::Base
 belongs_to :agent
end

#Schema - http://pastie.org/426261

def test_should_load_all_shops
  shop_1= Shop.create!
  shop_2= Shop.create!
  book= Book.create!(:distributor => Distributor.create!(:agents=> [Agent.create!(:shops => [shop_1, shop_2])]))


  loaded_version = Book.find(book.id, :include => [:distributor => {:agents => :shops}], :order => 'shops.id')

  assert(loaded_version.distributor.agents.first.shops.size == 2)
  #THIS ASSERTION FAILS WITH SHOPS.SIZE BEING 1, INSTEAD OF 2
end

你可能感兴趣的:(Ruby,ActiveRecord)