【发布时间】:2016-09-06 05:03:20
【问题描述】:
我为类别和产品创建了一个连接表。我的产品数据库中是否需要 category_id 列?当我进入我的 rails 控制台并输入 Product.new 时,没有类别属性。如果我想为产品分配类别,我该怎么做?这是我第一次使用连接表,我对它的工作原理感到困惑?
我的桌子:
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 %>
【问题讨论】:
标签: ruby-on-rails database has-and-belongs-to-many jointable