2

ネストされたカテゴリがあり、各カテゴリに多くのサブカテゴリがあり、各カテゴリが 1 つの親カテゴリに属している場合、Category モデルをどのように記述しますか?

私はそれが次のようなものになると思いました:

Category
belongs_to :category 
has_many   :categories

カテゴリ テーブルのどこにあるのですがparent_category_id、これは良い関係ですか? または、多対多の関係を示すために 2 番目のテーブルが必要ですか? belongs_to_and_has_many のようなものが必要だと思いますか?

任意のガイダンスをいただければ幸いです

4

3 に答える 3

2

マイケル・デュラントの答えは確かに正しいですが、それforeign_keyは電話で推測できますbelongs_toclass通話中の にも同じことが当てはまりhas_manyます。

そのため、Michael Durrant の回答のより簡潔なバージョン:

class Category < ActiveRecord::Base
  belongs_to :parent, class_name: 'Category'
  has_many :categories, foreign_key: :parent_id

  # Uses `parent_id` for the association
end
于 2012-08-07T18:06:30.947 に答える
2

これは の例とまったく同じですacts_as_tree

https://github.com/amerine/acts_as_treeをご覧ください

必要なのはparent_id列だけで、次のように言えます。

class Category
  include ActsAsTree
  acts_as_tree :order => "name"
end

その後、次のものにアクセスできます。

category.parent   # your parent
category.children # all the categories you are parent of
category.root     # the parent of any parents (or yourself)
category.ancestor # your parent, grandparent, ...
于 2012-06-06T04:41:13.480 に答える
1
class Category < ActiveRecord::Base

belongs_to :parent, :foreign_key => "parent_id", :class => "Category"
has_many :categories, :foreign_key => "parent_id", :class => "Category"

# Uses parent_id for the association.

has_and_belongs_to_many2 番目のテーブルは、この種の構造をマッピングするのに必要ではなく、適切でもありません。

于 2012-05-21T19:04:08.527 に答える