【发布时间】:2016-09-17 17:07:39
【问题描述】:
我正在开发一个 Rails 应用程序,并且正在对 API 进行版本控制。
关注RailsCast #350 我有这个:
routes.rb
namespace :v1 do
#resources for version 1
end
namespace :v2 do
#resources for version 2
end
我使用active_model_serializer,我有app/serializers/v1/ 和.../v2/ 与:
(对于 /v1)
module V1
class ResourceSerializer < ActiveModel::Serializer
attributes :id
end
end
(对于 /v2)
module V2
class ResourceSerializer < ActiveModel::Serializer
attributes :id, :data
end
end
但 Rails 不调用我的自定义序列化程序。
module V1
class ResourcesController < ApplicationController
def show
@resource = Resource.find(params[:id])
render json: @resource
end
end
end
输出为.../v1/resources/1
{"id":1,"name":"...","city":"...","created_at":"...","updated_at":"2..."}
而不是
{"id":1}
如果我放 render json: @resources, serializer: ResourceSerializer 它会检索 undefined method 'read_attribute_for_serialization'
任何帮助将不胜感激。谢谢!
编辑:命名空间有效!
【问题讨论】:
标签: ruby-on-rails json rest api ruby-on-rails-5