简体   繁体   English

Rails控制器类不从父类继承方法

[英]Rails controller class does not inherit a method from the parent class

I'm following a tutorial on how to create a REST Api using the rails-api gem. 我正在跟踪有关如何使用rails-api gem创建REST Api的教程。

In the tutorial, most of the API logic is encapsulated in the base class file app/controllers/api/v1/api_base_controller.rb 在本教程中,大多数API逻辑都封装在基类文件app/controllers/api/v1/api_base_controller.rb

module Api
  module V1
    class ApiBaseController < ApplicationController
      protect_from_forgery with: :null_session
      before_action :set_resource, only: [:destroy, :show, :update]
      respond_to :json

      private
      #Returns the resource from the created instance variable
      #@return [Object]
      def get_resource
        instance_variable_get("@#{resource_name}")
      end

      #Returns the allowed parameters for searching
      # Override this method in each API controller
      # to permit additional parameters to search on
      # @return [Hash]
      def query_params
        {}
      end

      #Returns the allowed parameters for pagination
      # @return [Hash]
      def page_params
        params.permit(:page, :page_size)
      end
      # The resource class based on the controller
      # @return [Class]
      def resource_class
        @resource_class ||= resource_name.classify.constantize
      end

      # The singular name for the resource class based on the controller
      # @return [String]
      def resource_name
        @resource_name ||= self.controller_name.singularize
      end

      #Only allow a trusted parameter "white list" through.
      # If a single resource is loaded for #create or #update,
      # then the controller for the resource must implement
      # the method "#{resource_name}_params" to limit permitted
      # parameters for the individual model.
      def resource_params
        @resource_params ||= self.send("#{resource_name}_params")
      end

      #Use callbacks to share common setup or constraints between actions.
      def set_resource(resource = nil)
        resource ||= resource_class.find(params[:id])
        instance_variable_set("@#{resource_name}", resource)
      end

      #POST /api/v1/{plural_resource_name}
      def create
        set_resource(resource_class.new(resource_params))

        if get_resource.save
          render :show, status: :created
        else
          render json: get_resource.errors, status: :unprocessable_entity
        end
      end

      #DELETE /api/v1/{plural_resource_name}/:id
      def destroy
       get_resource.destroy
        head :no_content
      end

      #GET /api/v1/{plural_resource_name}
      def index
        plural_resource_name = "@#{resource_name.pluralize}"
        resources = resource_class.where(query_params).page(page_params[:page]).per(page_params[:page_size])

        instance_variable_set(plural_resource_name, resources)
        respond_with instance_variable_get(plural_resource_name)
      end

      #GET /api/v1/{plural_resource_name}/1
      def show
        respond_with get_resource
      end

      #PATCH/PUT /api/{plural_resource_name}/1
      def update
        if get_resource.update(resource_params)
          render :show
        else
          render json: get_resource.errors, status: :unprocessable_entity
        end
      end
    end
  end
end

The model controllers inherit from this ApiBaseController one of the model controllers ( albums_controllers.rb ) looks like this: 模型控制器从此ApiBaseController继承模型控制器之一( albums_controllers.rb )如下所示:

module Api
  module V1
    class AlbumsController < Api::V1::ApiBaseController
      private
      def album_params
        params.require(:album).permit(:title)
      end

      def query_params
        params.permit(:title, :artist_id)
      end
    end
  end
end

I also have this in routes.rb 我在routes.rb也有这个

Rails.application.routes.draw do
  namespace :api, defaults: {format: 'json'} do
    namespace :v1 do
      resources :albums, :artists
    end
  end
end

when I do http://localhost:3000/api/v1/artists on the browser, i get this error: 当我在浏览器上执行http://localhost:3000/api/v1/artists时,出现此错误:

`The action 'index' could not be found for Api::V1::ArtistsController`

I have also noted that the ApplicationController generated by the rails-api gem inherits from ActionController::API and not ActionController::Base but i'm not sure whether this is the problem. 我还注意到,由rails-api gem生成的ApplicationController继承自ActionController::API ,而不继承自ActionController::Base但是我不确定这是否是问题。

private methods are not available to subclasses. private方法不适用于子类。 If you REALLY want to hide all of those methods but make it available to subclasses, use protected instead. 如果您确实要隐藏所有这些方法,但可将其提供给子类,请改用protected

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails api 控制器不从父类继承方法 - Rails api controller doesn't inherit method from the parent class 在Ruby on Rails中,子类是否继承父类的关联? - In Ruby on Rails, does a child class inherit the parent class' associations? 从 gem 继承控制器类 - Inherit controller class from gem 如何加载不直接从Rails 5中的Rails验证器类继承的自定义验证器? - How can I load a custom validator which does not directly inherit from a Rails validator class in Rails 5? Ruby on Rails-从父类为每个子类调用一个方法 - Ruby on Rails - Call a method for each subclass from the parent class Rails子类方法不会覆盖父类方法 - Rails subclass method not overwriting the parent class method 如何从控制器中的类方法访问路由路径? (导轨) - How to access route path from a Class method in a controller? (Rails) 如何在不继承ActiveRecord :: Base的类中使用Paperclip gem for Rails? - How can I use Paperclip gem for Rails in a class that does not inherit from ActiveRecord::Base? 是否可以从包含在rails中的父类中的模块中调用父类的子类的私有方法? - Is it okay to call a private method of a parent class's subclass from a module which is included in the parent class in rails? ruby类方法可以从另一个类继承吗? - Can a ruby class method inherit from another class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM