ruby-on-railsjsonviewjbuilder

How to render a collection in jbuilder?


There is a fantastic method in Rails to render a collection of objects for view templates, and it works as fellows:

<%= render @restaurants %>

It's automatically gonna look for a partial named _restaurant.html.erb, loop through collection, pass individual object to the partial, and render it. This is pretty fantastic.

Now, I'm looking for a very similar way in jbuilder gem.

_restaurant.json.jbuilder

json.(restaurant, :id, :name, :address, :latitude, :longitude)

Now, for @restaurants, how would I use this partial in the same way it works in Rails for view templates? For the time being, I'm rendering the collection the following way:

json.restaurants @restaurants do |restaurant|
  json.partial! restaurant
end

Solution

  • Ok, so I think you are looking for the below :

    json.partial! :restaurant, collection: @restaurants