我正在使用火箭裤来呈现我的JSON API。
我试图通过在我的模型中覆盖as_json来改变呈现JSON的方式,但不知何故,它似乎没有改变火箭裤响应中的任何东西。
在我的控制器中:
class Api::V1::ProjectsController < RocketPants::Base
...
def show
expose Project.find(params[:id])
end
...
end在我的模型中:
class Project < ActiveRecord::Base
...
def as_json(options = {})
{"this" => "is not working!"}
end
...
end我遗漏了什么?
发布于 2012-07-31 00:06:18
我已经知道如何做到这一点。火箭裤的工作方式是通过查看serializable_hash方法。覆盖它会导致响应发生变化。
编辑:
我得到的解决方案是:
在我需要添加一些属性的模型中:只需覆盖attributes方法:
# Overriding this method is required for the attribute to appear in the API
def attributes
info = {} # add any logic that fits you
super.merge info
end在需要公开API的控制器中,我创建了一个新的Model类(这只是为了保持不同的API版本),并覆盖了serializable_hash方法:
class Location < ::Location
def serializable_hash(options = {})
super only: [:id, :lat, :long],
include: [user: {only: ...your attributes here...}]
end
end发布于 2013-05-23 23:18:23
此外,还可以将第一组选项发送到expose块。根据源,您可以将选项传递给serializable_hash方法。例如:
expose user, only: [:name, :email]
这将在具有名称和电子邮件的对象上调用serializable_hash。
您还可以在这组选项中指定立即加载。例如:
expose uploads, :include => { :user => { :only => :username } }。
这将公开您的上传,并立即加载与用户的belongs_to关联。
来源:https://github.com/filtersquad/rocket_pants/issues/20#issuecomment-6347550
发布于 2014-04-04 23:26:33
对于嵌套的事物:
paginated @matches, include: { listing: { include: { company: { only: [:name, :email] } } } }
https://stackoverflow.com/questions/11493397
复制相似问题