has_and_belongs_to_many関連付けを使用して多対多の関係を持つ2つのモデル、項目、カテゴリがあります。私はRailsについて混乱していますhas_and_belongs_to_many Association
class Item < ActiveRecord::Base
has_and_belongs_to_many :categories
end
と
class Category < ActiveRecord::Base
has_and_belongs_to_many :items
end
を持って私のモデルで
私が参加し、テーブル "categories_items" 作成:私はすべてのエラーを取得しますが、私ではないよ
create_table "categories_items", :id => false, :force => true do |t|
t.integer "category_id"
t.integer "item_id"
end
をその協会が許していることについてちょっと混乱しています。私はいくつかのカテゴリ@categoryを持っている場合今、私は
@category.items
を行うことにより、その中のすべてのアイテムを見つけることができます私は
@item.categories
を行うことによって与えられた項目@itemに関連付けられているカテゴリを見つけることができると仮定しました
私は ActiveModel :: MissingAttributeErrorというエラーを取得しかし:欠落している属性を:カテゴリ
は、私がどのようにhas_and_belongs_to_manyアソシエーションの関連付け機能誤解、または私は私のコードで何かが欠けアム?ありがとうございました!
編集 - 追加情報:
私は混乱が私は項目/カテゴリを割り当てることになってる方法であると思います。私はあなたが前に一度を通過しているものを経験したと思う
@item = Item.new
... add attributes ...
@item.save
と
@category = Category.new
... add attributes ...
@category.save
をしてから
@category.items << @item
@item.categories << @category
ここであなたが持っているものは大丈夫だと思います。 '@ item'はどのように割り当てられていますか? – x1a4
私はあなたのコードをテストプロジェクト(Rails 3.2.1)に貼り付けました。 –
通常、MissingAttribute例外は、Model.select(「something」)。first.somethingelseを実行するとスローされます。実行中のコードとバックトレースをgitに貼り付けることはできますか? – bcd