Topic: How Can I Sort Returned Records Based On Virtual Attribute?

Hi everyone,

Sorry if this is a simple question - I'm totally new to all this.

I would like to build a site where the records returned as the result of a form submission are sorted according to a calculation based on attributes of the records and inputs from the form.

The Calculation would not be linear so I don't think I can create an attribute in the database to sort on and then just multiply it by the form input value when returning it to the results page.

I have thought of adding 10-100 attributes to calculate this value and then use the one that's closest to the input but I was hoping for a more elegant solution.

Any help with this would be much appreciated.

Cheers.

Re: How Can I Sort Returned Records Based On Virtual Attribute?

Sounds like you should sort the records with Ruby after you get the data back from the server,  the databases ability to sort is fairly limited when compared to what you can do with Ruby.

When you do a Find(:all, :conditions=>['whatever = ?', whatever]

it will return an array of found records.  You can then sort that array with Ruby,  based on whatever you wish. i.e.

param = params[:your_form][:some_value].to_i
data = FooBar.find(:all)
sorted = data.sort  do |x,y|
    a = x.attribute1.to_i * param
    b = y.attribute1.to_i * param
    a <=> b
end

If the dataset is very large this could be a bit of a problem.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: How Can I Sort Returned Records Based On Virtual Attribute?

Brad,

Thanks a lot for the quick and detailed reply. That's a great help.

Cheers!