У меня проблемы с именем ошибки в Ruby на рельсах. Получение неинициализированной константы User :: Авторы - PullRequest
1 голос
/ 25 марта 2020

Следующий вопрос в Rails. Когда я go на localhost: 3000 / Api / v1 / users, я получаю ошибку имени. неинициализированная константа User :: Авторы. Я не могу найти в чем ошибка. это указывает на мой контроллер пользователя, индекс. Как я покажу ниже.

Ошибка:

NameError in Api::V1::UsersController#index
uninitialized constant User::Authors
Extracted source (around line #8):
6  @users = User.all
7
8   render json: @users
9  end
10
11

  # # GET /users/1

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

Контроллер моих пользователей:

class Api::V1::UsersController < ApplicationController
  before_action :set_user, only: [:show, :update, :destroy]

  # # GET /users
  def index
    @users = User.all

    render json: @users
  end

  # # GET /users/1
  def show
    render json: @user
  end

  # POST /users
  def create
    @user = User.new(user_params)

    if @user.save
      render json: @user, status: :created, location: @user
    else
      render json: @user.errors, status: :unprocessable_entity
end
  end

  # PATCH/PUT /users/1
  def update
    if @user.update(user_params)
      render json: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  # DELETE /users/1
  def destroy
    @user.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def user_params
      params.require(:user).permit(:name, :username, :password_digest)
    end
end

На всякий случай я также публикую свой контроллер авторов.

Контроллер авторов

class Api::V1::AuthorsController < ApplicationController
  before_action :set_author, only: [:show, :update, :destroy]

  # GET /authors
  def index
    @authors = Author.all

    render json: @authors
  end

  # GET /authors/1
  def show
    render json: @author
  end

  # POST /authors
  def create
    @author = Author.new(author_params)

    if @author.save
      render json: @author, status: :created, location: @author
    else
      render json: @author.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /authors/1
  def update
    if @author.update(author_params)
      render json: @author
    else
      render json: @author.errors, status: :unprocessable_entity
    end
  end

  # DELETE /authors/1
  def destroy
    @author.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_author
      @author = Author.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def author_params
      params.require(:author).permit(:name)
    end
end

Мои маршруты

Rails.application.routes.draw do
  post "/api/v1/login", to: "sessions#create" 
  delete "/api/v1/logout", to: "sessions#destroy" 
  get "/api/v1/get_current_user", to: "sessions#get_current_user"
  namespace :api do
    namespace :v1 do   
      resources :comments
      resources :genres
      resources :authors
      resources :books
      resources :users do
        resources :books, only: [:index]
      end
    end
  end
end

Если есть что-то еще, что я должен показать, я могу обновить вопрос.

Заранее спасибо.

ОБНОВЛЕНИЕ:

Меня попросили добавить полную обратную трассировку:

activerecord (6.0.2.1) lib/active_record/inheritance.rb:206:in `compute_type'
activerecord (6.0.2.1) lib/active_record/reflection.rb:422:in `compute_class'
activerecord (6.0.2.1) lib/active_record/reflection.rb:769:in `klass'
activerecord (6.0.2.1) lib/active_record/associations/association.rb:137:in `klass'
activerecord (6.0.2.1) lib/active_record/associations/collection_association.rb:35:in `reader'
activerecord (6.0.2.1) lib/active_record/associations/builder/association.rb:100:in `authors'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:397:in `read_attribute_for_serialization'
active_model_serializers (0.10.10) lib/active_model/serializer/reflection.rb:168:in `value'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:17:in `object'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:50:in `serializer_class'
active_model_serializers (0.10.10) lib/active_model/serializer/lazy_association.rb:34:in `serializer'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:199:in `block (2 levels) in object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:357:in `yield'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:357:in `block (2 levels) in associations'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:352:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer.rb:352:in `block in associations'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:197:in `block in object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:7:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:7:in `each'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:194:in `object_cache_keys'
active_model_serializers (0.10.10) lib/active_model/serializer/concerns/caching.rb:179:in `cache_read_multi'
active_model_serializers (0.10.10) lib/active_model/serializer/collection_serializer.rb:25:in `serializable_hash'
active_model_serializers (0.10.10) lib/active_model_serializers/adapter/attributes.rb:14:in `serializable_hash'
active_model_serializers (0.10.10) lib/active_model_serializers/adapter/base.rb:61:in `as_json'
activesupport (6.0.2.1) lib/active_support/json/encoding.rb:35:in `encode'
activesupport (6.0.2.1) lib/active_support/json/encoding.rb:22:in `encode'
activesupport (6.0.2.1) lib/active_support/core_ext/object/json.rb:42:in `to_json'
active_model_serializers (0.10.10) lib/active_model_serializers/serializable_resource.rb:10:in `to_json'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:71:in `block (3 levels) in notify'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:112:in `block in run_callbacks'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:24:in `block (3 levels) in instrument_rendering'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:81:in `block in notify_render'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.2.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `instrument'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:80:in `notify_render'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:23:in `block (2 levels) in instrument_rendering'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:97:in `block in tag_logger'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:97:in `tag_logger'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:22:in `block in instrument_rendering'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:121:in `instance_exec'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:121:in `block in run_callbacks'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:139:in `run_callbacks'
active_model_serializers (0.10.10) lib/active_model_serializers/logging.rb:70:in `block (2 levels) in notify'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:157:in `block in <module:Renderers>'
active_model_serializers (0.10.10) lib/action_controller/serialization.rb:72:in `block (2 levels) in <module:Serialization>'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:150:in `block in _render_to_body_with_renderer'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/set.rb:338:in `each_key'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/set.rb:338:in `each'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:146:in `_render_to_body_with_renderer'
actionpack (6.0.2.1) lib/action_controller/metal/renderers.rb:142:in `render_to_body'
actionpack (6.0.2.1) lib/abstract_controller/rendering.rb:25:in `render'
actionpack (6.0.2.1) lib/action_controller/metal/rendering.rb:36:in `render'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
activesupport (6.0.2.1) lib/active_support/core_ext/benchmark.rb:14:in `block in ms'
/home/chaimsh/.rvm/rubies/ruby-2.6.1/lib/ruby/2.6.0/benchmark.rb:308:in `realtime'
activesupport (6.0.2.1) lib/active_support/core_ext/benchmark.rb:14:in `ms'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:85:in `cleanup_view_runtime'
activerecord (6.0.2.1) lib/active_record/railties/controller_runtime.rb:34:in `cleanup_view_runtime'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:43:in `render'
app/controllers/api/v1/users_controller.rb:8:in `index'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:196:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:135:in `run_callbacks'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:33:in `block in process_action'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.2.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `instrument'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
activerecord (6.0.2.1) lib/active_record/railties/controller_runtime.rb:27:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:136:in `process'
actionpack (6.0.2.1) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (6.0.2.1) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:51:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:33:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:49:in `block in serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `each'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:837:in `call'
rack (2.2.2) lib/rack/session/abstract/id.rb:266:in `context'
rack (2.2.2) lib/rack/session/abstract/id.rb:260:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/cookies.rb:648:in `call'
rack (2.2.2) lib/rack/etag.rb:27:in `call'
rack (2.2.2) lib/rack/conditional_get.rb:27:in `call'
rack (2.2.2) lib/rack/head.rb:12:in `call'
activerecord (6.0.2.1) lib/active_record/migration.rb:567:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:27:in `block in call'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:101:in `run_callbacks'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/actionable_exceptions.rb:17:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:32:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (6.0.2.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.2.2) lib/rack/runtime.rb:22:in `call'
activesupport (6.0.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/static.rb:126:in `call'
rack (2.2.2) lib/rack/sendfile.rb:110:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/host_authorization.rb:83:in `call'
rack-cors (1.1.1) lib/rack/cors.rb:100:in `call'
railties (6.0.2.1) lib/rails/engine.rb:526:in `call'
puma (4.3.3) lib/puma/configuration.rb:228:in `call'
puma (4.3.3) lib/puma/server.rb:682:in `handle_request'
puma (4.3.3) lib/puma/server.rb:472:in `process_client'
puma (4.3.3) lib/puma/server.rb:328:in `block in run'
puma (4.3.3) lib/puma/thread_pool.rb:134:in `block in spawn_thread'

ТАКЖЕ МОИ МОДЕЛИ. ДЛЯ МОДЕЛЕЙ, КОТОРЫЕ Я ОБМЕНЯЮТСЯ, ЕСТЬ БОЛЬШЕ МОДЕЛЕЙ, ЧЕМ ЭТО, НО Я УБИВАЮ, СООТВЕТСТВУЮЩИЕ ЕСТЬ ПОЛЬЗОВАТЕЛЬ И АВТОР

class User < ApplicationRecord
    has_secure_password

    has_many :books
    has_many :authors, through: :books
    has_many :genres, through: :books
    has_many :comments
    # has_many :comments, through: :books
    validates :username, uniqueness: true
end

И СЕЙЧАС ДЛЯ АВТОРА

class Author < ApplicationRecord

    has_many :books
    has_many :genres, through: :books
end

Ответы [ 2 ]

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

Поскольку это было правильно, я могу опубликовать его как правильный ответ вместо комментария.

Поскольку кажется, что у него возникают проблемы с поиском класса Author, вы можете проверить имя файла класса Author, просто чтобы он не был случайно сохранен как app / models / автор.rb (множественное число вместо единственного числа) или как-то еще. Кроме того, попробуйте явно сказать

has_many :authors, through: :books, class_name: '::Author'

в вашем классе User, просто чтобы увидеть, действительно ли он может найти его явно вместо логического вывода.

0 голосов
/ 27 марта 2020

Как известно, ответ был опубликован в комментариях @DanneManne. Спасибо!

- Явно произнесите has_many: авторы, через:: books, имя_класса: ':: Author' в вашем классе User, просто чтобы увидеть, может ли он найти его явно вместо предполагаемого.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...