2011-01-13 23 views
1

使用ruby 1.9.2和rails 3,我想限制當一個記錄被作爲json或xml(允許的唯一兩種格式)訪問時返回的字段。覆蓋to_xml來限制返回的字段

this非常有用的帖子介紹了我respond_with和我在網上找到了一個很好的方式來覆蓋允許/拒絕某些字段是覆蓋as_json或to_xml的類和設置:只有或:除了限制字段。

例如:

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]) 

但不覺得這是一個非常乾燥的方法。

+1

也許使用類似acts_as_api的東西雖然是一種更好的方法。 – jay

+0

認爲你必須調用你重寫'as_xml'的方法,類似於'as_json' – PerfectlyNormal

回答

5

在你to_xml方法,做到以下幾點:

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

這應該可以解決你。

+0

這可行!返回XML時,幫助我在CarrierWave中發現一個錯誤。 – Karl

+0

這也是爲了從XML輸出中排除列而使用Active Admin 1.0.0-pre2進入Rails 4的正確方法(因爲我無法在ActiveAdmin中找到鉤子以便以相同方式更改XML輸出你可以用CSV輸出)。 – Mattygabe