簡體   English   中英

Rails 4 ActionController :: Metal與序列化器

[英]Rails 4 ActionController::Metal with Serializers

我正在嘗試在Rails 4項目中使用ActionController :: Metal來制作API“基本”控制器,如下所示:

# 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錯誤的undefined method 'each' for nil:NilClass /api/v1/plans.json我認為Metal缺少一些我需要使用序列化程序的東西,但我不確定是什么?!

您必須在controller方法中專門渲染模板。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM