Ordering results with acts_as_taggable plugin

You may have noticed that when clicking on the individual tags below any particular post that you will be taken to a list of the most recent posts that also contain that tag. While this is great, it was a little flawed. You see, it wasn’t ordering the results properly! They should be ordered by the date they were posted. Well, as it turns out the fix for this was relatively simple (as most things in Ruby and Rails are).

Original code:

@posts = if tag_name = params[:id]
Tag.find_by_name(tag_name).tagged
else
Post.all_posts
end

Corrected code:

@posts = if tag_name = params[:id]
Post.find(:all, :include => ‘tags’, :conditions => ["tags.name = ?", params[:id]], :order => “posts.created_on DESC”)
else
Post.all_posts
end

Hopefully this helps anybody with a similar problem. When I was working on this I kept running into MySQL errors about an invalid column name, the “?” in the condition was all it took to fix that. I don’t really know what that “?” does, but it works!

Leave a Reply