April 20, 2006

Rails Sortable Column Headers With Associations

Filed under: Technology — mmrobins @ 1:33 pm

Of all the magic things Ruby on Rails does by default, I’m surprised they didn’t automatically create sortable column headers. I figured out my own way to do it, but I couldn’t figure out how to sort columns correctly when the data for that column contained a foreign key – until now.

For example, I have a requests table with an employee_id field. This is an integer that references the id of some employee in my employee table. Sorting those integers doesn’t alphabetically sort my request list based on who made the request.

I finally found a good lead to the solution from a modified version of SortHelper2, by Jonathan Conway. His code worked great for me as long as I did my list function like this:

def list
      sort_init('id', 'asc', nil, 'cheeses', true)
      sort_update
      @cheese_pages, @cheeses = paginate :cheeses, :per_page => 30, 
      :order =>   sort_clause, :include => [:cheese_maker]
end

But I defined some functions in my class that I use so that I don’t have to rewrite finds every time, so I had to use custom/classic pagination. This got me to wonder what the code looked like for the find statement. I finally figured out how to use the :include statement in the find command to sort by an association.

find( :all, :include => :employee, :conditions => ["resolved_on is null"], 
                          :order => "employees.name asc",
                          :limit  =>  @it_request_pages.items_per_page,
                          :offset =>  @it_request_pages.current.offset)

Normally I think the api documentation for rails is great, but how am I supposed to know how to do this from the find function definition of :include option (:include: Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. See eager loading under Associations). Okay, I guess there’s a decent example if you do find the eager loading section of the Associations definition.

No Comments »

No comments yet.

RSS feed for comments on this post. | TrackBack URI

Leave a comment

XHTML ( You can use these tags): <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .