1

私はいくつかのモデルを持っています

class Product < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

class Category < ActiveRecord::Base
  has_and_belongs_to_many :products
end

どうして言えないの

prod = Product.new
prod.categories << Category.new

インスタンスメソッドを追加する必要があるのに、has_and_belongs_to_manyクラスメソッドを追加するのはなぜですか?Product#categories<<

これらのクラスメソッドを使用して関連付けを設定するにはどうすればよいですか?

4

2 に答える 2

2

あなたが私に与えたエラーとコードで、それはおそらくあなたが見逃しているものです:

prod = Product.new              # This is a Product instance
prod.categories << Category.new # This works

prod = Product.where(name:'x')  # This returns a query (ActiveRecord::Relation) 
prod.categories << Category.new # This doesn't work

prod = Product.where(name:'x').first  # This is a Product instance
prod.categories << Category.new       # This works
于 2013-06-10T03:33:05.500 に答える
0

新しいオブジェクト (たとえばProduct) を作成するときは、.build メソッドを使用してそれらの関連付けを入力し、save を呼び出すことができます。

編集:ここでよく読んでください

于 2013-06-10T03:06:44.730 に答える