我知道如何全局禁用根元素,la Rails 3.1 include_root_in_json或使用ActiveRecord::Base.include_root_in_json = false
,但我只想爲幾個JSON請求(不是全局的)執行此操作。Rails:僅在特定的控制器操作中禁用JSON中的根目錄?
到目前爲止,我一直在做這樣的:
@donuts = Donut.where(:jelly => true)
@coffees = Coffee.all
@breakfast_sandwiches = Sandwich.where(:breakfast => true)
dunkin_donuts_order = {}
dunkin_donuts_order[:donuts] = @donuts
dunkin_donuts_order[:libations] = @coffees
dunkin_donuts_order[:non_donut_food] = @breakfast_sandwiches
Donut.include_root_in_json = false
Coffee.include_root_in_json = false
render :json => dunkin_donuts_order
Donut.include_root_in_json = true
Coffee.include_root_in_json = true
有大約5情況下,我有一個以上的模型要做到這一點,有時,它不覺得乾淨所有。我試圖把它放在around_filter
的位置上,但是例外情況正在打破這個流程,而且這也變得多毛。
必須有更好的方法!
這並不直接回答你的問題,但它確實回答了我來這裏尋找的問題:你可以抑制個人對'to_json'調用的根,例如'Donut.to_json(root:false)' – Lambart