我试图允许API请求指定要在对象上返回的字段.我只能使用指定的字段检索对象,但是当它被序列化时,它会抛出一个错误:
ActiveModel::MissingAttributeError (missing attribute: x)
Run Code Online (Sandbox Code Playgroud)
如何实现此功能ActiveModel::Serializer并且可能吗?
使用ruby 1.9.2和rails 3,我想限制以json或xml访问记录时返回的字段(只允许两种格式).
这个非常有用的帖子向我介绍了respond_with,我在网上找到了一条毯子允许/拒绝某些字段的好方法是覆盖类的as_json或to_xml并设置:only或:除限制字段外.
例:
class Widget < ActiveRecord::Base
def as_json(options={})
super(:except => [:created_at, :updated_at])
end
def to_xml(options={})
super(:except => [:created_at, :updated_at])
end
end
class WidgetsController < ApplicationController
respond_to :json, :xml
def index
respond_with(@widgets = Widgets.all)
end
def show
respond_with(@widget = Widget.find(params[:id]))
end
end
Run Code Online (Sandbox Code Playgroud)
这正是我正在寻找的并适用于json,但对于xml"index"(GET /widgets.xml),它以空的Widget数组进行响应.如果我删除to_xml覆盖我得到预期的结果.我做错了什么,和/或为什么Widgets.to_xml覆盖会影响Array.to_xml结果?
我可以通过使用来解决这个问题
respond_with(@widgets = Widgets.all, :except => [:created_at, :updated_at])
Run Code Online (Sandbox Code Playgroud)
但不要觉得这是一种非常干燥的方法.