0
カテゴリと製品の結合テーブルを作成しました。製品データベースにcategory_id列が必要ですか?私が自分のレールコンソールに入ってProduct.newと入力すると、カテゴリ属性はありません。カテゴリを製品に割り当てる場合は、どうすればいいですか?これは私の初めての結合テーブルでの作業であり、どのように動作するのか混乱していますか?テーブルの結合HABTMの結合
マイテーブル:
create_table "categories", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "category_id"
end
create_table "categories_products", id: false, force: :cascade do |t|
t.integer "category_id", null: false
t.integer "product_id", null: false
end
create_table "products", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image", default: "{}"
end
マイ団体:私の製品フォームの
class CategoryProduct < ActiveRecord::Base
belongs_to :category
belongs_to :product
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories
has_many :categories_products
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
has_many :categories_products
end
カテゴリ部分:
<% for category in Category.all %>
<div>
<%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category) %>
<%= category.name %>
</div>
<% end %>
説明応答いただき、誠にありがとうございますあなたのレールのコンソールで、次のような製品にカテゴリを割り当てることができます。この記事は、HABTMの関連性をもっとよく理解するのに役立ちました。 – Kris