0

我有ProductCategories模型。

每个产品可以有多个类别。每个类别将有许多产品。

我最好做 2HABTM还是has_many关系?

有人告诉我,它HABTM已被弃用 - 这是真的吗?

此外,对于两者,我假设我将不得不使用连接表categories_products。我该如何创建它?只是定期迁移?

谢谢。

4

1 回答 1

1

顶部(数字)的示例。更新。

    class Product < ActiveRecord::Base
      has_many :category_products do
                def with_categories
                  includes(:category)
                end
              end
      has_many :categories, :through => :category_products

      def top_categories(number)
        category_products.with_categories.order("purchases_count DESC").limit(number).map {|c| c.category} # category included
      end

    end

    class Category < ActiveRecord::Base
      has_many :category_products do
                def with_products
                  includes(:product)
                end
              end
      has_many :products, :through => :category_products

      def top_products(number)
        category_products.with_products.order("purchases_count DESC").limit(number).map {|c| c.product} # product included
      end

    end

    class CategoryProduct < ActiveRecord::Base
      belongs_to :product
      belongs_to :category

      validates_uniqueness_of :product_id, :scope => :category_id

      # attribute :purchases_count, :default => 0
    end
于 2012-12-17T23:30:16.293 回答