1

我試圖使用的ActionController ::金屬在Rails 4項目,使一個API「基地」控制如下:軌道4的ActionController ::金屬與串行器

# app/controllers/api/v1/base_controller.rb 
class Api::V1::BaseController < ActionController::Metal 
    include AbstractController::Rendering 
    include ActionController::ImplicitRender 
    include ActionController::Serialization 
    include ActionController::MimeResponds 
    include AbstractController::Callbacks 
end 

我則繼承這在我的每個API控制器,例如:

# app/controllers/api/v1/plans_controller.rb 
class Api::V1::PlansController < Api::V1::BaseController 
    def index 
    @plans = Plan.all 

    if params[:ids] 
     @plans = @plans.where(id: params[:ids]) 
    end 
    end 

    def show 
    @plan = Plan.find(params[:id]) 
    end 

    private 
    def plan_params 
     params.require(:plan).permit(:name) 
    end 
end 

我想用ActiveModel::Serializers產生了我的API的JSON響應,我創建了以下串行:

# app/serializers/plan_serializer.rb 
class PlanSerializer < ActiveModel::Serializer 
    attributes :id, :name, :created_at, :updated_at 
end 

當我嘗試加載我的API端點(/api/v1/plans.json)時,我目前得到undefined method 'each' for nil:NilClass錯誤 - 我認爲Metal中缺少一些我需要使用序列化程序的東西,但我不確定是什麼?!

+0

如果您嘗試使用ActionController :: Metal,您的控制器+序列化程序是否正在工作? – Simon

回答

0

您必須在控制器方法中專門呈現您的模板。例如:

def show 
    @plan = Plan.find(params[:id]) 
    render :show 
end 
+0

我想你錯過了一個右括號。 – Dan

+0

你說得對。固定! – philipDS