我有2个模型,关联many_to_many。在创建品牌时,我有错误:
Admin :: Brands中的NameError #new 显示/.../app/views/admin/brands/_form.html.slim,其中第3行引发: 未初始化的恒定品牌:: BrandCatalog
我做错了什么?
#app/models/category.rb
class Category < ActiveRecord::Base
has_many :brand_catalogs
has_many :brands, through: :brand_catalogs
end
#app/models/brand.rb
class Brand < ActiveRecord::Base
has_many :brand_catalogs
has_many :categories, through: :brand_catalogs
end
#app/models/brandcatalog.rb
class BrandCatalog < ActiveRecord::Base
belongs_to :category
belongs_to :brand
end
迁移
#db/migrate/20151230092013_create_brand_catalogs.rb
class CreateBrandCatalogs < ActiveRecord::Migration
def change
create_table :brand_catalogs, id: false do |t|
t.integer :category_id
t.integer :brand_id
end
add_index :brand_catalogs, [:category_id, :brand_id]
end
end
品牌控制器
#app/controllers/admin/brands_controller.rb
class Admin::BrandsController < Admin::BaseController
before_action :require_login
load_and_authorize_resource
before_action :load_brand, only: [:edit, :update, :destroy]
def index
@brands = Brand.all
end
def new
@brand = Brand.new
end
def edit
end
def create
@brand = Brand.create(brand_params)
if @brand.save
redirect_to admin_brands_path, notice: 'Brand was successfully created.'
else
render :new, notice: 'Something wrong!'
end
def update
end
def destroy
end
private
def load_brand
@brand = Brand.find(params[:id])
end
def brand_params
params.require(:brand).permit(:title, {category_ids: []})
end
end
品牌形式
# views/admin/brands/_form.html.slim
= bootstrap_form_for [:admin, @brand] do |f|
div class='form-group'
= f.collection_check_boxes(:category_ids, Category.all, :id, :title)
div class='form-group'
= f.text_field :title, class: 'form-control'
= f.submit 'Save', class: 'btn btn-success'
答案 0 :(得分:1)
尝试将#app/models/brandcatalog.rb
文件重命名为brand_catalog.rb
。模型名称需要具有匹配的文件名,但需要使用下划线而不是camelcase。
例如,名为ThisIsMyModel
的模型应将其文件命名为this_is_my_model.rb