override to_xml to limit fields returned
Asked Answered
C

1

1

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.

Caroche answered 13/1, 2011 at 21:47 Comment(2)
maybe using something like acts_as_api would be a better approach in general though.Caroche
think you have to call the method you override as_xml, similar to as_jsonFidgety
J
5

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.

Juan answered 29/7, 2011 at 19:43 Comment(2)
This works! Helped me with a bug in CarrierWave when returning XML.Convalescence
This was also the proper way to go in Rails 4 with Active Admin 1.0.0-pre2 in order to exclude columns from XML output (since I wasn't able to find a hook within ActiveAdmin in order to change XML output the same way you can with CSV output).Sergias

© 2022 - 2024 — McMap. All rights reserved.