Do you have a massive list of items in a scaffold-type arrangement (e.g. in a typo-style admin)? Here's a way to quickly and easily filter and sort your big-assed list. Note: this requires the Hash#to_sql function posted here a few weeks ago .. told you it was useful! More after the jump.. First, we're going to tackle filtering; if y'all want sorting or ajax, too, please leave some comments to motivate me to write the second half. Just so I know you care :) Like any good web coder (har, har) let's start with the view. We have articles, they're organized into simple categories (Category model), written by authors (Author.find(:all) is stored in @authors)


...


Now, that's the header.. it looks something like this:


Post title
Post title
The giant monkey returnsMonkeysJoe
Who's the biggest, grayest mofo?ElephantsFred

Finally, some pagination:



Now, you may notice there's some javascript in those Select boxes: onchange='filtering();'. Here's that function.


Hopefully that's fairly self-explanatory; it builds a query string from the values of the two select boxes. Next: onto the controller.

class ArticleController < ApplicationController
  def list
    # create a conditions hash from our params, if they exist
    @conditions[:main_category_id] = Category.find_by_permalink(params[:category]).id if params[:category] and !params[:category].empty?
    @conditions[:user_id] = params[:author] if params[:author] and !params[:author].empty?

    @content_pages = Paginator.new self, Article.count, 10, @params['page'].to_i
    @contents = Article.find(:all, :conditions => @conditions.to_sql, :order => 'published_at desc', :offset => @params['page'].to_i, :limit => 10)

    @authors = Author.find_by_sql("SELECT DISTINCT(content.user_id), users.* FROM #{Article.table_name} LEFT JOIN users ON content.user_id = users.id WHERE content.type = 'Article' ORDER BY users.nickname ASC")
    # this is our fairly specific sql, yours is probably much different.

    @categories = Category.find(:all)
    @authors = Author.find(:all)
  end

end
Voila! We now have dropdown filtering.

4 Responses to “Scaffolding on Crack (sortable, filtered scaffolds)”

  1. atmos Says:
    Pimp as usual, do share the ajax versions. :)
  2. jesus peanuce Says:
    have you seen this? kinda easier... http://wiki.rubyonrails.com/rails/pages/Sort+Helper
  3. court3nay Says:
    Hah. Did you even read the code? I didn't cover sorting at all. Also, sort helper badly wants plugin-izing..
  4. Yanni Says:

    Cool.

Leave a Reply

I am a human (check this)

Remember: escape your underscores \_ and indent code at least 4 spaces or incur the wrath of smartypants.