私はモデルを持っProduct
ていCategories
ます。
各製品には多くのカテゴリを含めることができます。各カテゴリには多くの製品があります。
私は2HABTM
またはhas_many
関係を行う方が良いですか?
HABTM
非推奨になっていると言われましたが、本当ですか?
また、どちらの場合も、結合テーブルを使用する必要があると思いますcategories_products
。どうすれば作成できますか?定期的な移行ですか?
ありがとう。
私はモデルを持っProduct
ていCategories
ます。
各製品には多くのカテゴリを含めることができます。各カテゴリには多くの製品があります。
私は2HABTM
またはhas_many
関係を行う方が良いですか?
HABTM
非推奨になっていると言われましたが、本当ですか?
また、どちらの場合も、結合テーブルを使用する必要があると思いますcategories_products
。どうすれば作成できますか?定期的な移行ですか?
ありがとう。
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