【问题标题】:Rails 4 ActionController::Metal with SerializersRails 4 ActionController::Metal 和序列化器
【发布时间】:2014-05-09 20:48:08
【问题描述】:

我正在尝试在 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 错误 - 我认为 Metal 中缺少一些东西,我需要这些东西才能使用序列化程序,但我不确定是什么?!

【问题讨论】:

  • 如果您尝试使用 ActionController::Metal,您的控制器 + 序列化程序是否正常工作?

标签: ruby-on-rails json serialization ruby-on-rails-4 active-model-serializers


【解决方案1】:

您必须在控制器方法中专门呈现您的模板。例如:

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

【讨论】:

  • 我认为您缺少右括号。
猜你喜欢
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
相关资源
最近更新 更多