To create an indexed view of either all of the items (in a normal index view), or filtered based on an association, you can do the following. For example, if you have a many to many relationship between "users" and "tags", and you wish an index view of users filtered on whether they contain a particular tag, you can do the following:
In the tag index view:
1
2 <h1>Listing tags</h1>
3
4 <table>
5 <tr>
6 <th>Name</th>
7 </tr>
8
9 <% for tag in @tags %>
10 <tr>
11 <td><%=h tag.name %></td>
12 <td><%= link_to 'Users', user_path(:tag_id=>tag) %></td>
13 <td><%= link_to 'Show', tag_path(tag) %></td>
14 <td><%= link_to 'Edit', edit_tag_path(tag) %></td>
15 <td><%= link_to 'Destroy', tag_path(tag), :confirm => 'Are you sure?', :method => :delete %></td>
16 </tr>
17 <% end %>
18 </table>
19 <br />
20 <%= link_to 'New tag', new_tag_path %>
Note that
1 user_path(:tag_id=>tag)
translates to
1 <a href="/users?tag_id=1">Users</a>
.
In the controller for users, modify the index and change the standard @users=User.find(:all) to
1
2 @tag=Tag.find(params[:tag_id]) if params[:tag_id]
3 @users = @tag.users || throw rescue User.find(:all)
The
1 throw rescue
was because the @tag.users could throw an exception as well as having a nil value, and this is DRYer than coding it as
1
2 @users = @tag.users || User.find(:all) rescue User.find(:all)
Full details at
Displaying a subset of items from an association.