Search code examples
javascriptruby-on-railsjsonruby-on-rails-4jbuilder

Using jbuilder to access child objects in has many relationship


Trying to use jbuilder with gon gem to pass an object and its child objects to javascript, where object is a lender and it has many children, which are inventories. Following instructions from gon gem here, but I'm maintaining that this is a question on the jbuilder side, not gon... you'll see why.

Current code to fetch lenders:

#/test.json.builder

json.lenders @lenders, :email, :latitude, :longitude

Test Action in Controller code

@lenders = Signups.all
gon.jbuilder

#/test.html.erb

<script>
  console.log(gon.lenders)
</script>

This is working fine, and produces the following output:enter image description here

However, when I try to fetch the children inventories using standard jbuilder code per Ryan Bates' show notes, like so:

#/test.json.builder

json.lenders @lenders, :email, :latitude, :longitude
json.inventories @lenders.inventories, :id, :itemlist_id, :description

I get the error: undefined methodinventories' for #`

I get why I'm getting the error, because per output above, the result of @lenders is an array of the lenders, not the lender objects themselves, but then how else do I get the inventories? My desired goal is that the output looks as above, but that for each object, there is an inventories field which produces an array of the individual inventory objects, each with the attributes id, itemlist_id and description.


Things I've tried that have produced same error:

ONE other variation of getting to child per Ryan Bates

json.comments @article.comments do |json, comment|
  json.partial! comment
end

#in partial
  json.(comment, :id, :name, :content)

TWO including inventories in controller code

Test Action in Controller code

@lenders = Signups.all.includes(:inventories)
gon.jbuilder

And this is not a gon problem, gon is installed after jbuilder in gemfile, and I am including it in the view header.


Solution

  • Ok this worked:

    #/test.json.builder

    json.array!(@lenders) do |json, lender|
      json.(lender, :id, :email, :latitude, :longitude)
      json.inventories lender.inventories do |json, inventory|
        json.(inventory, :id, :itemlist_id, :description)
      end
    end    
    

    Drawn from this answer