使用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])
但不覺得這是一個非常乾燥的方法。
也許使用類似acts_as_api的東西雖然是一種更好的方法。 – jay
認爲你必須調用你重寫'as_xml'的方法,類似於'as_json' – PerfectlyNormal