20

現在、Ruby on Rails に関するプロジェクトを行っています。product という名前のエンティティを作成し、category という名前の他のエンティティに多対多の関係を設定したいと考えています。

script/generate scaffold product prd_name:string category:references 

このコードを実行すると、1 対 1 のマッピングのみが可能になります。ハードコーディングせずに多対多を設定するにはどうすればよいですか?

4

4 に答える 4

30

You should not expect to be able to generate your app via scaffolding alone. It is meant only to provide an example for getting started.

The most flexible kind of many-to-many relationship in rails is called has many through. This requires a join table which would typically be called 'categorisations' in this case. It would need a product_id column declared as belongs to :product and a category_id column declared as belongs_to :category. The three models (including the join model) would be declared thus:

# Table name: products
# Columns:
#   name:string

class Product < ActiveRecord::Base
  has_many :categorisations, dependent: :destroy
  has_many :categories, through: :categorisations
end

# Table name: categories
# Columns:
#   name:string

class Category < ActiveRecord::Base
  has_many :categorisations, dependent: :destroy
  has_many :products, through: :categorisations
end

# Table name: categorisations
# Columns:
#   product_id:integer
#   category_id:integer

class Categorisation < ActiveRecord::Base
  belongs_to :product
  belongs_to :category
end

Note that I've named the columns name rather than prd_name since this is both human-readable and avoids redundant repetition of the table name. This is highly recommended when using rails.

The models can be generated like this:

rails generate model product name
rails generate model category name
rails generate model categorisation product:references category:references

As for generating the scaffolding, you could replace model with scaffold in the first two commands. Again though, I don't recommend it except as a way to see an example to learn from.

于 2012-10-29T06:44:47.177 に答える
-2

足場を介してこれを行うことはできません。クラスのモデルを編集して、多対多の関係を設定する必要があります。

于 2012-11-30T09:26:27.993 に答える