Reputation: 1596
What's the best way to extract the related data from a has many through relationship?
If my tasks and categories are joined through categorizations, I'd like to display a list of tasks and their related categories in my index view.
I've tried putting the following in my controller:
@tasks = Task.find(:all, :include => :taskcategories )
However that fails.
In my view, I tried this:
<% for task in @tasks %>
<li><%= task.title %> <%= task.taskcategory_name %></li>
<% end %>
That also fails.
Upvotes: 0
Views: 90
Reputation: 25757
Given your association definitions are right, you can just:
@tasks = Task.find(:all, :include => :categories)
... and within the view:
<% for task in @tasks %>
<li><%= task.title %> <%= task.categories.map{|c| c.name}.join(', ') %></li>
<% end %>
Upvotes: 1