开发者

Shortening up respond_with( :include => xxx)

开发者 https://www.devze.com 2023-03-25 05:17 出处:网络
I\'m looking for a way to shorten up the :include => :child inside a respond_with which generates json.

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 开发者_JAVA百科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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号