Rails - NameError - неинициализированная константа - PullRequest
0 голосов
/ 19 марта 2020

Я понимаю, что это за ошибка, но я не вижу ошибки в своем коде. Контроллер - множественное число, модель - единственное число, а имя таблицы - множественное число.

Ошибка при посещении индекса:

NameError at / admin / custom_communities неинициализированная константа Admin :: CustomCommunitiesController :: CustomCommunity

Сгенерированный контроллер: (файл: controllers / admin / custom_communities_controller.rb)

# frozen_string_literal: true

class Admin::CustomCommunitiesController < Admin::BaseController
  before_action :set_custom_community, only: [:show, :edit, :update, :destroy]

  def index
    @custom_communities = CustomCommunity.page(params[:page])
  end

  def show; end

  def new
    @custom_community = CustomCommunity.new
  end


  def edit; end


  def create
    @custom_community = CustomCommunity.new(custom_community_params)

    respond_to do |format|
      if @custom_community.save
        format.html { redirect_to @custom_community, notice: "Custom community was successfully created." }
        format.json { render :show, status: :created, location: @custom_community }
      else
        format.html { render :new }
        format.json { render json: @custom_community.errors, status: :unprocessable_entity }
      end
    end
  end


  def update
    respond_to do |format|
      if @custom_community.update(custom_community_params)
        format.html { redirect_to @custom_community, notice: "Custom community was successfully updated." }
        format.json { render :show, status: :ok, location: @custom_community }
      else
        format.html { render :edit }
        format.json { render json: @custom_community.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @custom_community.destroy
    respond_to do |format|
      format.html { redirect_to admin_custom_communities_url, notice: "Custom community was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private

    # Use callbacks to share common setup or constraints between actions.
    def set_custom_community
      @custom_community = CustomCommunity.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def custom_community_params
      params.require(:custom_community).permit(:name, :description, :picture, :should_delete_picture)
    end
end

Модель: (файл: models / custom_community.rb)

# frozen_string_literal: true

class CustomCommunity < ApplicationRecord
end

Миграция:

class CreateCustomCommunities < ActiveRecord::Migration[5.2]
  def change
    create_table :custom_communities do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end

Маршруты: в административных маршрутах:

resources :custom_communities

1 Ответ

1 голос
/ 19 марта 2020

Я уверен, что кто-то еще может объяснить, почему, но бывают случаи, когда rails будет думать, что следующий класс в методе index:

class Admin::CustomCommunitiesController < Admin::BaseController
  def index
    CustomCommunity.all
  end
end

ссылается на класс, определенный в Admin::CustomCommunitiesController, т.е. он думает, что вы пытаетесь позвонить Admin::CustomCommunitiesController::CustomCommunity.all. Чтобы «освободить пространство» от класса, попробуйте:

# frozen_string_literal: true

class Admin::CustomCommunitiesController < Admin::BaseController
  before_action :set_custom_community, only: [:show, :edit, :update, :destroy]

  def index
    @custom_communities = ::CustomCommunity.page(params[:page])
  end

  def show; end

  def new
    @custom_community = ::CustomCommunity.new
  end


  def edit; end


  def create
    @custom_community = ::CustomCommunity.new(custom_community_params)

    respond_to do |format|
      if @custom_community.save
        format.html { redirect_to @custom_community, notice: "Custom community was successfully created." }
        format.json { render :show, status: :created, location: @custom_community }
      else
        format.html { render :new }
        format.json { render json: @custom_community.errors, status: :unprocessable_entity }
      end
    end
  end


  def update
    respond_to do |format|
      if @custom_community.update(custom_community_params)
        format.html { redirect_to @custom_community, notice: "Custom community was successfully updated." }
        format.json { render :show, status: :ok, location: @custom_community }
      else
        format.html { render :edit }
        format.json { render json: @custom_community.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @custom_community.destroy
    respond_to do |format|
      format.html { redirect_to admin_custom_communities_url, notice: "Custom community was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private

    # Use callbacks to share common setup or constraints between actions.
    def set_custom_community
      @custom_community = ::CustomCommunity.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def custom_community_params
      params.require(:custom_community).permit(:name, :description, :picture, :should_delete_picture)
    end
end

Я думаю, что это все из них. В основном переключите каждый CustomCommunity вызов класса на ::CustomCommunity, чтобы освободить его от имени.

...