override to_xml to limit fields returned

2019-07-25 06:48发布

问题:

using ruby 1.9.2 and rails 3, i would like to limit the fields returned when a record is accessed as json or xml (the only two formats allowed).

this very useful post introduced me to respond_with and i found somewhere online that a nice way to blanket allow/deny some fields is to override as_json or to_xml for the class and set :only or :except to limit fields.

example:

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

this is exactly what i am looking for and works for json, but for xml "index" (GET /widgets.xml) it responds with an empty Widget array. if i remove the to_xml override i get the expected results. am i doing something wrong, and/or why does the Widgets.to_xml override affect the Array.to_xml result?

i can work around this by using

respond_with(@widgets = Widgets.all, :except => [:created_at, :updated_at])

but do not feel that is a very DRY method.

回答1:

In your to_xml method, do the following:

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

That should fix you up.