【问题标题】:Polymorphic associations in Rails 3Rails 3 中的多态关联
【发布时间】:2011-03-01 02:44:24
【问题描述】:

我觉得我快疯了。

假设我有 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

地址是多态的,因为最终我将使用它来存储客户、人员、员工等的地址。此外,每个地址都可以是特定类型:账单、运输、工作、家庭等。

我正在尝试在页面上提取一些信息。

@some_warehouse = Warehouse.first

那么在我看来:

%b= @some_warehouse.name
%b= @some_warehouse.billing_address.address_line_1

等等

我最终会查找每一行信息。

我尝试做类似的事情

Warehouse.includes(:addresses).where(:name => "Ware1")
Warehouse.joins(:addresses).where(:name => "Ware1")

以及它的各种变体。 无论我做什么,我都无法让导轨预加载所有表格。我做错了什么?

【问题讨论】:

    标签: ruby-on-rails polymorphism


    【解决方案1】:

    这里是修改后的模型,可以在 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
    

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

    【讨论】:

      【解决方案2】:

      也许你想使用preload_associations

      【讨论】:

      • 不完全是我想要的,但读起来很有趣。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多