override to_xml to limit fields returned

旧时模样 提交于 2019-12-24 09:44:49

问题


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.



来源:https://stackoverflow.com/questions/4685662/override-to-xml-to-limit-fields-returned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!