Search code examples
ruby-on-railsjsonrabl

RABL collection appears empty in template but not in controller


I'm currently using rabl-rails 0.5.3 and Rails 4.2.6

I've got this problem where I'm attempting to render a collection of my College objects from the index method of a Rails controller.

Here's a simplified version of the index method in my controller:

  def index
    @colleges = College.all

    puts @colleges.count

    render 'api/data_bridge/colleges/show'
  end

I see '100' for the output of the puts statement there. Some clearly @colleges is not empty.

Here is the rabl index template:

puts "---===========================-"
puts @colleges.inspect
puts "---===========================-"
collection @colleges

In my server output I'm seeing those puts statements looking like:

---===========================-
nil
---===========================-

When I dump the @colleges in the controller, it's definitely not nil. I can't figure out what happened to the data between the controller and the template.


Solution

  • Documentation as source for my claims: https://github.com/ccocchi/rabl-rails#overview

    Your rabl file should look like this:

    puts "---===========================-"
    puts :@colleges.inspect
    puts "---===========================-"
    collection :@colleges
    

    This was their example:

    # app/views/post/index.rabl
    collection :@posts
    attributes :id, :title, :subject
    child(:user) { attributes :full_name }
    node(:read) { |post| post.read_by?(@user) }
    

    Pay close attention to the ":" in front of the symbol. Here is why:

    The fact of compiling the template outside of any rendering context prevent us to use any instances variables (with the exception of node) in the template because they are rendering objects. So instead, you'll have to use symbols of these variables.For example, to render the collection @posts inside your PostController, you need to use :@posts inside of the template.