我知道如何全局禁用根元素,a la Rails 3.1 include_root_in_json或使用 ActiveRecord::Base.include_root_in_json = false
,但我只想为一些 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
s,但异常(exception)打破了流程,这也变得毛茸茸的。一定会有更好的办法!
最佳答案
不幸的是,答案是肯定和否定。
是的,你在上面所做的可以说可以做得更好。不,Rails 不会让您在每个操作的基础上添加根。 JSON 渲染的构建并没有考虑到这种灵活性。
话虽如此,这就是我要做的:
include_root_in_json
至 false
对于那些根据操作具 Root过的模型(例如上面的 Donut
和 Coffee
)。 as_json
以允许更大的灵活性。下面是一个例子:# in model.rb
def as_json(options = nil)
hash = serializable_hash(options)
if options && options[:root]
hash = { options[:root] => hash }
else
hash = hash
end
end
这个例子将使您可以选择传递一个根,但默认为无根。你也可以用另一种方式来写。
as_json
,您必须适本地修改渲染调用。所以,对于 Donut
,你会做 render :json => @donut.to_json
. 希望这可以帮助!
关于ruby-on-rails - rails : Disable root in JSON for only specific controller actions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7250762/