← Home

Patch Mephisto to add a comments list filter

The controller part

The filter keyword can be put into the URL parameters like in admin/comments?filter=toyota so nothing needs to be changed in the routes. We can access the parameter right away in the controller action with params[:filter].

Thus all that's needed here is to change the index action of Admin::CommentsController to constrain the selected comments by the keyword if one is present.

That's easy. We'll just replace this line:


@comments = site.unapproved_comments.find(:all, :include => :article)

... by this slightly longer piece of code:


condition = [:body, :author, :author_url].collect do |column|
  "contents.#{column} LIKE '%#{params[:filter]}%'"
end.join(' OR ') unless params[:filter].blank?
@comments = site.unapproved_comments.find(:all, :include => :article,
  :conditions => condition)

That's all. You now can try and add a filter=something parameter to your URL and the comments list should be filtered accordingly.

Later on we might want to refactor this and move the condition building and querying stuff into the Site or Comment model.

The view part

Everything that remains to do now is to add some kind of HTML form to the admin interface that allows to enter a keyword and sends it to the appropriate action.

I've added the following to the admin/comments/index.rhtml template:


<!-- begin action nav -->
<div id="page-nav">
  ...
</div>
<div id="filter" class="manual">
  <form action="">
    <label>Filter</label>
    <input type="text" name="filter" value="<%= params[:filter] %>">
  </form>
</div>
<!-- /end action nav -->

And adjusted the design with the following addition to the mephisto.css stylesheet (located in the public/stylesheets/mephisto directory):


#filter {
	...
  height: 35px;
}
#filter form {
  float: right;
  margin: 6px;
  font-weight: bold;
  text-shadow: #FFFFFF 2px 2px;
}

Here's a patch

I've filed away a patch for my personal backup purposes: admin_filter_comments_list.diff. I believe it should work with any default Mephisto installation as well.