【问题标题】:Join table HABTM association加入表 HABTM 关联
【发布时间】: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


    【解决方案1】:

    您已经有了 HABTM 连接表,因此您不需要在 products 表中包含 category_id。

    您可以在 Rails 控制台中为产品分配类别,例如以下内容

    product = Product.create(..)
    category = Category.create(..)
    product.categories << category //assigning category to product
    

    这里举例说明HABTM

    【讨论】:

    • 非常感谢您的回复。这篇文章帮助我更好地理解了 HABTM 关联。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多