2

I'm trying to use RABL to build JSON output for the following index.html.erb file:

<% @halls.each do |hall| %>
<%= hall.name.capitalize %><br><br>
<% hall.days.each do |day| %>
    <%= day.date.capitalize %>
    <br><br>    
    <% day.meals.each do |meal| %>
        <%= meal.name.capitalize %><br><br>
        <% meal.foods.each do |food| %>
            <%= food.name %> <br>
        <% end %>
     <br>
    <% end %>
<% end %>
   <% end %>

At this point, I've tried it a million different ways, and I was hoping someone could help me generate the code for the index.json.rabl file, as I'm completely and utterly stuck.

AlexSBerman
  • 37
  • 1
  • 5

1 Answers1

4

If you want to do "deep-nesting" of the child nodes, try this out:

collection @halls

# Use a custom node to get capitalized name
node :name do |hall|
  hall.name.capitalize
end

# Child list of days
child :days do
  node :date do |day|
    day.date.capitalize
  end

  child :meals do
    node :name do |meal|
      meal.name.capitalize
    end
    child :foods do
      # No need to use custom node because we don't need to do extra processing on the value (i.e capitalization is not required) and 'name' is a simple attribute on the model.
      attribute :name
    end
  end
end

Otherwise, if you want all the child nodes all at the same level, then don't nest the do blocks.

Also, check out the RailsCast on RABL. One of the biggest concepts that took me a while to get is which object is in "scope" for the various RABL blocks (i.e. child block, node block, etc.) The RailsCast does a decent job of explaining the scoping of the object.

richsinn
  • 1,341
  • 1
  • 12
  • 27