0

私はモデルを持っProductていCategoriesます。

各製品には多くのカテゴリを含めることができます。各カテゴリには多くの製品があります。

私は2HABTMまたはhas_many関係を行う方が良いですか?

HABTM非推奨になっていると言われましたが、本当ですか?

また、どちらの場合も、結合テーブルを使用する必要があると思いますcategories_products。どうすれば作成できますか?定期的な移行ですか?

ありがとう。

4

1 に答える 1

1

top(number)の例。更新しました。

    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 に答える