缩短 respond_with( :include => xxx)

发布于 2024-11-27 18:55:57 字数 544 浏览 5 评论 0原文

我正在寻找一种方法来缩短 :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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

简单爱 2024-12-04 18:55:57

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

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:

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

That should let you clean up your controller a bit, you only need this:

@parent = Parent.find(params[:id])
respond_with @parent
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文