Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include has_many results in REST JSON result

I have a Model called List that has_many :entries. As usual, Rails 3 generated this show method for List

def show
    @list = List.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @list }
    end
end

How can I change format.json to include the entries results from @list in the json response as well?

I know I could convert @list to a Hash, add the Hash value of .entries to that, then render the Hash, but I suspect that Rails has a more elegant trick up its sleeve.

like image 867
Cory Gagliardi Avatar asked Apr 15 '12 05:04

Cory Gagliardi


1 Answers

Yes, there's an :include option you can give to to_json:

format.json { render json: @list.to_json(:include => :entries) }
like image 69
tsherif Avatar answered Nov 19 '22 01:11

tsherif