覆盖to_xml以限制返回的字段

时间:2011-01-13 21:47:03

标签: ruby-on-rails-3 respond-to respond-with

使用ruby 1.9.2和rails 3,我想限制以json或xml(仅允许两种格式)访问记录时返回的字段。

this非常有用的帖子向我介绍了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

这正是我正在寻找的并适用于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])

但不要觉得这是一种非常干燥的方法。

1 个答案:

答案 0 :(得分:5)

在to_xml方法中,执行以下操作:

def to_xml(options={})
  options.merge!(:except => [:created_at, :updated_at])
  super(options)
end

这应该可以帮到你。