[ActiveRecord] :order in has_many

I have the following definition

class A < ActiveRecord::Base
has_many bs, :order => ‘fecha ASC, id ASC’
end

somewhere in my app, I need to sort them differently:

some_a = A.find(something)
some_b = a.bs.find(:first,
:conditions => [‘fecha <= ?’, some_date],
:order => ‘fecha DESC, id DESC’)

this is creating the following SQL:

SELECT * FROM bs WHERE (bs.a_id = 1 AND (fecha <= ‘2007-02-01’)) ORDER
BY fecha DESC, id DESC, fecha ASC, id ASC LIMIT 1

wich is really weird… How can I replace the order of the relation only
for that query? Looking at the rails code[1], it seems that the only
(simple) way to do that would be to manually do the relation, something
like this:

some_b = B.find(:first,
:conditions => [‘a_id = ? AND fecha <= ?’,
some_a.id,
some_date],
:order => 'fecha DESC, id DESC)

[1] active_record(1.15.1)/associations/has_many.rb, line 81
if options[:order] && @reflection.options[:order]
options[:order] = “#{options[:order]},
#{@reflection.options[:order]}”
elsif @reflection.options[:order]
options[:order] = @reflection.options[:order]
end

line 82 seems to be where the :orders are mixed. Which is fine if
they’re not the same columns…

any idea?
regards,
Rolando.-

On 2/1/07, Rolando A. [email protected] wrote:

some_b = a.bs.find(:first,
(simple) way to do that would be to manually do the relation, something
options[:order] = "#{options[:order]},
Rolando.-
Jamis just blogged about this recently:

http://weblog.jamisbuck.org/2007/1/18/activerecord-association-scoping-pitfalls

Scroll down towards the bottom to see examples of both solving the
problem using a second extension and using association extensions.

Hope that helps.


Zack C.
http://depixelate.com

Zack C. wrote:

Jamis just blogged about this recently:

Buckblog: ActiveRecord association scoping pitfalls

nice!!!
thanks a lot :smiley:

Scroll down towards the bottom to see examples of both solving the
problem using a second extension and using association extensions.

Hope that helps.


Zack C.
http://depixelate.com

Regards,
Rolando.-