简体   繁体   中英

Multiple Child Models and Nesting RABL — Works in HTML

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.

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 (ie child block, node block, etc.) The RailsCast does a decent job of explaining the scoping of the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM