使用 ruby 1.9.2 和 rails 3,我想限制以 json 或 xml 访问记录时返回的字段(仅允许两种格式)。
这个非常有用的帖子向我介绍了respond_with,我在网上的某个地方发现了一个全面允许/拒绝某些字段的好方法是覆盖类的as_json或to_xml并设置:only或:except来限制字段。
例子:
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
这正是我正在寻找并适用于 json 的内容,但对于 xml“索引”(GET /widgets.xml),它以一个空的 Widget 数组响应。如果我删除 to_xml 覆盖,我会得到预期的结果。我做错了什么,和/或为什么 Widgets.to_xml 覆盖会影响 Array.to_xml 结果?
我可以通过使用解决这个问题
respond_with(@widgets = Widgets.all, :except => [:created_at, :updated_at])
但不觉得这是一个很DRY的方法。