Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
ActiveRecord find order by method
4 Posts
ActiveRecord find order by method

Hi, I need help:

I want to sort a list by a method, NOT through a database column, example

class MyClass < ActiveRecord::Base

#this method return true or false def is_a_local_customer

#stub

end

#this method return true or false def is_a_regional_customer

#stub

end end

....

MyClass.find(:all, :order=> 'is_a_local_customer,is_a_regional_customer,last_name')

o something similar(may me named_scope, or :order, etc)

thanks

So long as you dont paginate you can do MyClass.all.sort_by(&:is_a_local_customer) etc, sorting after the record has been pulled out. If you do paginate i recommend you cache those values on the record.

Hi Juan, I agree with James.

An alternative syntax, assuming you have defined: is_a_local_customer(some_parameter) in MyClass class, for example, is:

MyClass.all.sort_by {|r| [r. is_a_local_customer(some_parameter), r.last_name, r.name]}

//or the same

some_collection.sort_by {|r| [r. is_a_local_customer(some_parameter), r.last_name, r.name]}

The pagination also works fine for me.

Greetings

Person
Forum Rating: 100
Sign In To Rate Post

Thanks

4 Posts
Login to add your message