我试图使用以下方法为产品分配多个类别
class Category < ActiveRecord::Base
has_many :categories_products
has_many :products, :through => :categories_products
validates :name, presence: true, length: { maximum: 255 }
end
class CategoryProduct < ActiveRecord::Base
belongs_to :category
belongs_to :product
end
class Product < ActiveRecord::Base
has_many :categories_products
has_many :categories, :through => :categories_products
end产品控制器
def new
form_info
if @categories.empty?
flash[:notice] = 'You must create a category before you create a product.'
redirect_to new_admin_merchandise_prototype_url
else
@product = Product.new
@product.categories << @categories
# @product.category = Category.new
end
end产品视图
.mdl-grid
.mdl-cell.mdl-cell--12-col
h3.mdl-typography--display-1.teal-heading= t('.title')
.mdl-grid
.mdl-cell.mdl-cell--12-col.card-item-type--volume
.mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--12-col
= form.text_field :name, class: 'mdl-textfield__input', required: true
= form.label :name, class: 'mdl-textfield__label'
.mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--12-col
= form.text_area :keywords, class: 'mdl-textfield__input'
= form.label :keywords, class: 'mdl-textfield__label'
.mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--12-col
= form.text_area :description, class: 'mdl-textfield__input'
= form.label :description, class: 'mdl-textfield__label'
.mdl-grid
.mdl-cell.mdl-cell--6-col
h3.mdl-typography--display-1.teal-heading Categories
.mdl-grid
.mdl-cell.mdl-cell--12-col.card-item-type--volume
.mdl-grid
- @categories.each_slice((@categories.count/3).ceil) do |cg|
.mdl-cell.mdl-cell--3-col
- cg.each do |c|
label.mdl-checkbox.mdl-js-checkbox.mdl-js-ripple-effect.mdl-cell.mdl-cell--12-col for=c.id
= form.check_box :categories, :class => 'mdl-checkbox__input', :id => c.id
span.mdl-checkbox__label= c.name.titlecase
.mdl-grid
.mdl-cell.mdl-cel--12-col
= form.submit class: 'mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent'错误
NameError: uninitialized constant Product::CategoriesProduct发布于 2016-12-23 13:28:40
您正面临一个命名问题:
您的模型名为CategoryProduct。检查创建表的迁移:它很可能如下所示:
create_table :category_products do |t|
t.belongs_to :product
t.belongs_to :category
t.timestamps
end这里的重要部分是:category_products。相同的表名将出现在您的db/schema.rb中
如果您还没有看到它:产品是单一的,而类别是多元化的。
然后,这一关系中出现了一个问题:
has_many :categories_products在找到正确模型的过程中,rails使用.,它只对字符串中的最后一个单词进行奇异化。
运行'categories_products'.singularize返回
=> "categories_product“
因此,rails正在寻找一个模型CategoriesProduct,却找不到它。检查您的错误消息;)
解决这一问题的方法有三种:
1)更改表名
使用rake db:rollback撤消迁移,将名称更改为定义的表名为category_products,然后再次迁移。
2)更改模型名
将文件更改为categories_product,将模型更改为CategoriesProduct
3)在关系中指定join_table
has_many :categories_products, :join_table => :category_products不要这样做--这是一个丑陋的解决办法--去做吧。
https://stackoverflow.com/questions/41296276
复制相似问题