【发布时间】:2011-01-13 21:47:02
【问题描述】:
使用 ruby 1.9.2 和 rails 3,我想限制以 json 或 xml 访问记录时返回的字段(仅允许两种格式)。
this 非常有用的帖子向我介绍了 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 的方法。
【问题讨论】:
-
也许使用像 act_as_api 这样的东西通常会是更好的方法。
-
认为你必须调用你覆盖的方法
as_xml,类似于as_json
标签: ruby-on-rails-3 respond-to respond-with