Order by dynamic field

Hello,

If I have the following model:

class MyModel < ActiveRecord::Base
def self.some_calculations(id)

end
end

Is it possible to use MyModel.find() and order the results by my defined
method self.some_calculations(id)?


Thanks in advance,
Justas

Yes, why not?

class MyModel < ActiveRecord::Base
def self.some_calculations(id)
find(:all, :conditions => [‘id != ?’, id], :order => ‘rand()’)
end
end

MyModel.some_calculations(66)

OR drop the self and have an instance method…

class MyModel < ActiveRecord::Base
def some_calculations
find(:all, :conditions => [‘id != ?’, id], :order => ‘rand()’)
end
end

MyModel.find(66).some_calculations

On Mar 11, 2007, at 11:52 AM, Justas wrote:

method self.some_calculations(id)?
To accomplish that you need to fetch all the involved rows, and order
the objects in Ruby land:

@models = MyModel.find_all_by_foo(foo).sort {|a, b| … }

Of course that may be too expensive, depending on the amount of data.
If that was the case, you could consider maintaining those
calculations via AR callbacks and cache them in some column. That
way, you’d delegate ordering to the database.

– fxn

On Mar 11, 2007, at 3:10 PM, eden li wrote:

class MyModel < ActiveRecord::Base
def self.some_calculations(id)
find(:all, :conditions => [‘id != ?’, id], :order => ‘rand()’)
end
end

Justas wants to order the rows according to the result of applying
some_calculations() to them.

– fxn

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs