views:

27

answers:

1

I am following Ryan Bates' railscast on Sortable Table Columns and I have successfully gotten a column to sort ascending and descending.

My table is more complex than in the Railscast because I have columns from different tables.

# controller
@cars = Car.find(:all).order(sort_column + " " + sort_direction).includes(:manufacturers)


#view
<%= sortable "age" %>

How do you add sortable columns for related tables such as manufacturers?

+1  A: 

I had a similar issue. Got it fixed with something like:

 <%= sortable "manufacturers.name", "Manufacturer name" %>
 <%= sortable "cars.age", "Age" %>

The sort function in the application_controller should be something like this:

 def sort_column
     ['manufacturers.name', 'cars.age'].include?(params[:sort]) ? params[:sort] : 'cars.age'
 end
cristian
Hi Cristian, it's not working unfortunately. It does work within the same table but not using your code above to sort on other columns. Are you sure this exact code worked?
sscirrus
I've given more details on the answer. Does it work now ?
cristian
Hi Christian, I played around for 30 minutes and started to get it working - I needed some controller and view tweaks to get it. Here's the final challenge: one of my sortable fields is a class method of cars entitled 'efficiency', which is a calculation based on two of cars' other fields (divide one field by the other). It isn't finding cars.efficiency :)
sscirrus
You might want to try and store the 'efficiency' in another column. That would work faster and simpler. Basically a before filter sets that value. The sorting should be obvious afterwards.
cristian
Thanks a lot for all your help Cristian. Have a great day!
sscirrus