Jenny Blunt
Jenny Blunt

Reputation: 1596

has_many through fetching related values

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

Answers (1)

moritz
moritz

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

Related Questions