Tha*_*ick 2 ruby ruby-on-rails include arel respond-with
我正在寻找一种方法来缩短:include =>:在respond_with中生成json的child.
这是一个例子,不确定它是否可能,但我想知道.
在控制器中:
@p = Parent.where('id = ?', params[:id])
respond_with(@p, :include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}})
Run Code Online (Sandbox Code Playgroud)
在我定义实例时,是否有一些包含这些内容?
也许是这样的:
@p = Parent.includes(:child1, :child2, :child3, :grandchild1).where('id = ?', params[:id])
respond_with(@p)
Run Code Online (Sandbox Code Playgroud)
基本上,我正在尝试干掉我的代码...我不想一直反复输入包含哈希...是否有一些只包括所有子对象的一次调用?
ActiveRecord有一个as_json方法,用于定义如何将对象输出为json.您可以默认使用此方法包含关联的子项,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
这应该让你稍微清理你的控制器,你只需要这个:
@parent = Parent.find(params[:id])
respond_with @parent
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2504 次 |
最近记录: |