缩短 respond_with( :include => xxx)
我正在寻找一种方法来缩短 :include => :child 位于 respond_with 中,生成 json。
这是一个例子,不确定是否可能,但我想找出答案。
在控制器中:
@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)
基本上,我正在尝试干燥我的代码...我不想一遍又一遍地输入包含哈希...是否有某种方法可以在一次调用中包含所有子对象?
I'm looking for a way to shorten up the :include => :child inside a respond_with which generates json.
Here is an example, not sure if it is even possible, but I would like to find out.
In the controller:
@p = Parent.where('id = ?', params[:id])
respond_with(@p, :include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}})
Is there someway to include these all when I define the instance?
Maybe something like:
@p = Parent.includes(:child1, :child2, :child3, :grandchild1).where('id = ?', params[:id])
respond_with(@p)
Basically, I'm trying to DRY up my code ... I don't want to have to keep typing the include hash over and over ... Is there someway to just include all child objects in one call?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ActiveRecord 有一个 as_json 方法,定义对象应如何输出为 json。您可以 ovveride 此方法以默认包含关联的子项,如下所示:
这应该让您稍微清理一下控制器,您只需要这样:
ActiveRecord has an as_json method that defines how the object should be outputted as json. You can ovveride this method to include the associated children by default so something like this:
That should let you clean up your controller a bit, you only need this: