[英]Context-Sensitive JSON Response
我正在创建一个由RESTful json控制器组成的Rails 3后端。 例如,控制器看起来像这样:
respond_to :json
def index
...
respond_with resources
end
...
这由客户端上的jQuery使用。 一切都很好。
我的下一步是控制JSON,以便根据上下文不对某些属性进行序列化。 例如,资源所有者比仅具有读访问权的人获得更多的属性下传。
目前,我倾向于使用Draper,并根据用户的角色为每个模型使用单独的装饰器。
我的问题是,这会产生很多样板。 我目前也在使用cancan进行基于角色的授权。
谁能建议一种更好的方法来实现这一目标?
我建议使用ActiveModel :: Serializer。 参见https://github.com/josevalim/active_model_serializers
为要公开的每个资源创建一个序列化器。 然后,您可以为每个模型分离序列化逻辑,轻松地公开其他方法,并根据角色确定每个模型的范围。 与CanCan搭配使用效果很好。
我喜欢这种语法,例如:
class MonkeySerializer < ActiveModel::Serializer
attributes :name, :mom, :weight
private
# use this for a custom attribute not on the model
def weight
monkey.weight_in_pounds
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.