覆盖to_xml以限制返回的字段

jay*_*jay 1 respond-to respond-with ruby-on-rails-3

使用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)

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

Ale*_*mer 5

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

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

这应该会解决你的问题.