alexin
alexin

Reputation: 243

Uninitialized constant many_to_many association in Rails4

I have 2 model with the association many_to_many. When creating a brand I have error:

NameError in Admin::Brands#new Showing /.../app/views/admin/brands/_form.html.slim where line #3 raised: uninitialized constant Brand::BrandCatalog

What am I doing wrong?

#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

migration

#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

brands controller

#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

brands form

# 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'

Upvotes: 0

Views: 351

Answers (1)

nbon
nbon

Reputation: 2805

Try renaming your #app/models/brandcatalog.rb file to brand_catalog.rb. Modelnames needs to have matching filenames but with underscore instead of camelcase.

For example a model called ThisIsMyModel should have its file named this_is_my_model.rb

Upvotes: 1

Related Questions