Search code examples
ruby-on-railsjsonrabl

passing an object to render( :template => "template.json.rabl") in RoR 3


I need to embed json into html and in the #322 RailsCasts says the way to do it using RABL...

app/views/places/show.html.erb
<div id="place" data-place="<%= render(template: "places/show.json.rabl") %>" >

here is my rabl template

app/views/places/show.json.rabl
object  @place
attributes :id, :name, :desc, :address
node(:type) { |place| place.type_place.name }

child :photos do 
  attributes :id, :desc
  node(:url) { |photo| photo.image.url(:square) }
end

and It is working fine but I want to render the rabl-template in other view like:

app/views/places/finder.html.erb
<%= @places.each do |place| %>
  <div id="place-<%= place.id %>" data-place="<%= render(template: "places/show.json.rabl") %>" >
<% end %>

it shows me the next message error

undefined method `type_place' for nil:NilClass

Extracted source (around line #1):

1: object  @place
2: attributes :id, :name, :desc, :address
3: 
4: node(:type) { |place| place.type_place.name }

from the message I think the error is what I'm not passing the object place to the template... I was trying a lot and I didn't get this.

Thanks in advance, and sorry for my english


Solution

  • You need to explicitly call Rabl::Renderer

    <%= @places.each do |place| %>
        <div id="place-<%= place.id %>" data-place="<%= Rabl::Renderer.json(place, 'places/show', view_path: 'app/views') %>" >
    <% end %>