Rails中的多态关联3

kon*_*ung 6 polymorphism ruby-on-rails

我想我会疯了.

假设我有3个型号:地址,仓库,类别:

class Address < ActiveRecord::Base
  belongs_to :category
  belongs_to :addressable, :polymorphic => true

  scope :billing_addresses , where(:categories => {:name => 'billing'}).joins(:category)  
  scope :shipping_addresses , where(:categories => {:name => 'shipping'}).joins(:category) 

end 


class Category < ActiveRecord::Base
  has_many :addresses
  has_many :subcategories, :class_name  => "Category", :foreign_key => "category_id"
  belongs_to :category, :class_name => "Category"  
end


class Warehouse < ActiveRecord::Base
  has_many :addresses, :as => :addressable
end
Run Code Online (Sandbox Code Playgroud)

地址是多态的,因为最终我将用它来存储客户,人员,员工等的地址.而且每个地址都可以是某种类型:计费,运输,工作,家庭等.

我想在页面上提取一些信息.

@some_warehouse = Warehouse.first
Run Code Online (Sandbox Code Playgroud)

然后在我看来:

%b= @some_warehouse.name
%b= @some_warehouse.billing_address.address_line_1
Run Code Online (Sandbox Code Playgroud)

等等.

我最终对每行信息进行查找.

我试着做的事情

Warehouse.includes(:addresses).where(:name => "Ware1")
Warehouse.joins(:addresses).where(:name => "Ware1")
Run Code Online (Sandbox Code Playgroud)

以及各种变化.无论我做什么,我都无法通过轨道预加载所有表格.我究竟做错了什么?

kon*_*ung 8

以下是修改后的模型,它们在sql中进行适当的连接,并将问题数量从16减少到8,每个信息对应一个,而不是同时执行查找类别的倍数等等:

class Address < ActiveRecord::Base
  belongs_to :category
  belongs_to :addressable, :polymorphic => true

  scope :billing_addresses ,  where(:categories => {:name => 'billing'}).includes(:category)
  scope :shipping_addresses , where(:categories => {:name => 'shipping'}).includes(:category)

end

class Warehouse < ActiveRecord::Base
  has_many :addresses,  :as => :addressable,  :include => :category, :dependent => :destroy

  def billing_address
    self.addresses.billing_addresses.first
  end    
  def shipping_address
    self.addresses.shipping_addresses.first
  end   
end


class Category < ActiveRecord::Base
  has_many :addresses
  has_many :subcategories, :class_name  => "Category", :foreign_key => "category_id"
  belongs_to :category, :class_name => "Category"  
end
Run Code Online (Sandbox Code Playgroud)

睡眠有帮助.也不要忘记不时重新加载控制台:-)