1

I'm using handles_sortable_columns to sort my columns in Rails 3 and was wondering if there is a way to sort by a column in another table other than using a join.

I have a column that is a lookup of the name of a column in another table.

That is, I have cities.country_id as a column and in the View template I do:

@cities.each do |city|
    city.country.name

to display the name.

I would like to be able to sort by this column, but the countries.name, not the cities.country_id.

Does anyone know if this possible with the gem or any other simple way? If so how?

The only thing I can think of is to do an IF statement in the controller and catch the sorting by country and then run a different query using a join for that, but that's ugly and error-prone, was hoping for something more elegant.

Thanks.

3 Answers 3

1

Can you override to the to_s on the country model to return the name, then sort by that in the controller?

In your country model override to_s by:

def to_s
 country.name
end

Then in your controller

@sorted_cities = @cities.sort_by { |obj| obj.country.to_s }
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I don't understand what you mean
This is really interesting. I'd never seen it before. In the end I went with a join so I could also query on the country name, but thanks a lot for pointing this out. I'll have to give it a try.
1

in addition to Webjedi answer..

 @sorted_cities = @cities.includes(:country).sort_by { |obj| obj.country.to_s } #for eager loading

1 Comment

Don't do this. You should use the database.
0

In the end I decided to use a join to get the right data to begin with. While Webjedi's answer is quite intriguing I didn't want to override any built-in functions, but it's good to know I can do that.

The code looks like this:

@countries = Country.select('countries.*, continents.name AS continent_name').joins{continent}.search(params[:term]).order(order).page(params[:page])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.