【发布时间】:2016-01-07 19:26:15
【问题描述】:
我是编程和 Rails 的新手,有些东西我不完全理解。 我正在创建一个应用程序
product has_many categories
category has_many products
如果我理解正确,我需要创建一个连接表 products_categories,它有一个product_id 和一个category_id。首先,我还需要这张桌子的模型吗?如果是的话,我想它看起来像这样:
class CategoryProduct < ActiveRecord::Base
belongs_to :category
belongs_to :product
end
以及 product.rb 中的其他模型:
class Product < ActiveRecord::Base
has_many :category_products
has_many :categories, through: :category_product
has_attached_file :picture,
styles: { medium: "300x300>", thumb: "100x100>" }
validates_attachment_content_type :picture,
content_type: /\Aimage\/.*\z/
validates :price, presence: { message: "Merci d'indiquer le prix du produit" }
validates :name, presence: { message: "Merci d'indiquer le nom du produit" }
validates :weight, presence: { message: "Merci d'indiquer le poids du produit" }
validates :description, presence: { message: "Merci d'écrire une description du produit " }
end
在 category.rb 中
class Category < ActiveRecord::Base
has_many :category_products
has_many :products, through: :category_product
validates :name, presence: { message: "Merci d'indiquer le nom de la catégorie" }
end
现在假设我想创建一个产品,在创建它的同时,从类别列表中为该产品指定尽可能多的类别。
到目前为止,在我看来,这是我的 Product/new.html.slim :
div class="container marged-top"
div class= "col-xs-12 col-md-offset-3 col-md-5 bigmarge"
div class="panel panel-default"
div class= "panel-heading"
h4 Création Produit
div class= "panel-body"
=simple_form_for @product, html: { multipart: true } do |t|
= t.error_notification
= t.input :name, label: 'Nom'
= t.input :description, label: 'Description', required: true
= t.input :price, label: 'Prix', required: true
= t.input :weight, label: 'Poids', required: true
= t.label :picture
= t.file_field :picture
= t.association :categories, as: :check_boxes
= t.button :submit, value: "Valider", class: "btn-success marge-bas"
这是我的 Product 实例的简单表单。我想我现在需要一个 CategoryProduct 的表格吗? 如果我希望用户能够在创建产品时向产品添加他想要的任意数量的类别,我该如何更改?
这是 category_product 表的迁移文件:
类 CreateTableCategoriesProducts <:migration>
def change
create_table :categories_products do |t|
t.references :product, index: true
t.references :category, index: true
end
add_foreign_key :categories_products, :categories
add_foreign_key :categories_products, :products
end
end
我用以下迁移文件重命名了之前的表:
class RenameTableCategoriesProducts < ActiveRecord::Migration
def self.up
rename_table :categories_products, :category_products
end
def self.down
rename_table :category_products, :categories_products
end
end
我在 product/new.html.slim 的 simple_form 上收到以下错误:
undefined method `klass' for nil:NilClass
代码在这里中断:
= t.association :categories, as: :check_boxes
所以我猜我的联想还不是很正确
【问题讨论】:
标签: ruby-on-rails forms model jointable