【发布时间】:2016-03-05 07:48:48
【问题描述】:
我有一个简单的 Rails 应用程序,它为 User、Article、Comments 模型提供 CRUD。
我需要公开 RESTful API 以从 3rd 方服务中使用它。我为/api/v1/.... 请求添加了一个单独的命名空间并使用了Active Model Serializers。但它影响了现有代码以及UsersController、ArticlesController 与视图之间的所有交互,因为整个应用程序中的序列化已完全改变。
有什么方法可以让序列化器只与 API 控制器一起工作?
这里有一些代码:
class UserSerializer < ActiveModel::Serializer
attributes :name, :email # because I want expose only these attributes in API
has_many :articles # and show only articles in the API
end
API 控制器:
module Api
class UsersController < Api::BaseController
def index
render json: User.includes(:articles) # this is API handler and I want only this controller to use the serializers
end
end
end
但我希望现有的UsersController 能够工作,因为我没有任何序列化程序。现有的控制器是一个典型的控制器,有视图模板等等。
所以问题是向项目添加序列化程序(用于 API 控制器)破坏了现有的控制器,render json: 在几个地方。
更新: 在路线中:
- 普通用户控制器:
resources :users - api 用户控制器:
namespace :api { resources :users }
【问题讨论】:
-
你能发布一些代码吗?比如你如何在你的应用中添加 AMS 以及你如何映射你
UsersController等等? -
@Surya 当然,添加了一些
-
文档说 Rails 将首先查找序列化程序(github.com/rails-api/… - 向上滚动一行):“在这种情况下,Rails 将查找名为
PostSerializer的序列化程序,如果它存在, 用它来序列化 Post。”。这就是为什么在其他控制器中render json:对象正在使用 AMS 进行序列化。
标签: ruby-on-rails ruby api serialization