Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Filtering based on a has_and_belongs_to_many association (See related posts)

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:
<h1>Listing tags</h1>

<table>
  <tr>
    <th>Name</th>
  </tr>

<% for tag in @tags %>
  <tr>
    <td><%=h tag.name %></td>
    <td><%= link_to 'Users', user_path(:tag_id=>tag) %></td>
    <td><%= link_to 'Show', tag_path(tag) %></td>
    <td><%= link_to 'Edit', edit_tag_path(tag) %></td>
    <td><%= link_to 'Destroy', tag_path(tag), :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
  <% end %>
</table>
<br />
<%= link_to 'New tag', new_tag_path %>


Note that
user_path(:tag_id=>tag)
translates to
<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

    @tag=Tag.find(params[:tag_id]) if params[:tag_id]
    @users = @tag.users || throw rescue User.find(:all)


The
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
    @users = @tag.users || User.find(:all) rescue User.find(:all)


Full details at Displaying a subset of items from an association.

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts