使用2个has_many关系还是2个HABTM?

时间:2012-12-17 22:58:19

标签: ruby-on-rails ruby-on-rails-3

我有ProductCategories型号。

每个产品可以有很多类别。每个类别都有很多产品。

我最好做2 HABTMhas_many关系吗?

我被告知HABTM被弃用了 - 这是真的吗?

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

感谢。

1 个答案:

答案 0 :(得分: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