【问题标题】:override to_xml to limit fields returned覆盖 to_xml 以限制返回的字段
【发布时间】:2011-01-13 21:47:02
【问题描述】:

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

this 非常有用的帖子向我介绍了 respond_with,我在网上的某个地方发现了一种全面允许/拒绝某些字段的好方法是覆盖类的 as_json 或 to_xml 并设置 :only 或 :except 以限制字段。

示例:

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“索引”(GET /widgets.xml),它会以一个空的 Widget 数组进行响应。如果我删除 to_xml 覆盖,我会得到预期的结果。我做错了什么,和/或为什么 Widgets.to_xml 覆盖会影响 Array.to_xml 结果?

我可以通过使用来解决这个问题

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

但不觉得这是一种非常 DRY 的方法。

【问题讨论】:

  • 也许使用像 act_as_api 这样的东西通常会是更好的方法。
  • 认为你必须调用你覆盖的方法as_xml,类似于as_json

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


【解决方案1】:

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

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

这应该可以解决您的问题。

【讨论】:

  • 这行得通!在返回 XML 时帮助我解决了 CarrierWave 中的一个错误。
  • 这也是在 Rails 4 中使用 Active Admin 1.0.0-pre2 的正确方法,以便从 XML 输出中排除列(因为我无法在 ActiveAdmin 中按顺序找到挂钩以与 CSV 输出相同的方式更改 XML 输出)。
猜你喜欢
  • 1970-01-01
  • 2012-05-10
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
相关资源
最近更新 更多