![](/img/trans.png)
[英]Setting up custom formats for respond_to and respond_with in Ruby on Rails 4
[英]Shortening up respond_with( :include => xxx)
我正在尋找一種方法來縮短可生成json的response_with中的:include =>:child。
這是一個示例,不確定是否可能,但我想找出答案。
在控制器中:
@p = Parent.where('id = ?', params[:id])
respond_with(@p, :include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}})
在定義實例時,是否有某種方式可以將所有這些都包括在內?
也許像這樣:
@p = Parent.includes(:child1, :child2, :child3, :grandchild1).where('id = ?', params[:id])
respond_with(@p)
基本上,我正在嘗試烘干我的代碼...我不想不必一遍又一遍地鍵入include哈希值...是否有可能只在一次調用中包括所有子對象?
ActiveRecord有一個as_json方法,該方法定義如何將對象輸出為json。 您可以ovveride此方法默認情況下包括關聯的子級,如下所示:
class Parent < ActiveRecord::Base
# We went to display grandchildren by default in the output JSON
def as_json(options={})
super(options.merge(:include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}})
end
end
那應該讓您稍微清理一下控制器,您只需要這樣做:
@parent = Parent.find(params[:id])
respond_with @parent
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.