Tuesday, 10 September 2013

How to use has_many in rails view

How to use has_many in rails view


Here is the index_controller

  def index
    @categories = Category.all
  end

Here is the two models

1. Category model

has_many :sub_categories

2. sub_category model

belongs_to :category

And your view should contain

<% @categories.each do |category| %>
    <h1><%= category.title %></h1>
    <% category.sub_categories.each do |sub_category| %>
        <%= sub_category.descriptino %>
    <% end %>
<% end %>

No comments:

Post a Comment