Forum: Ruby on Rails [ActiveRecord] :order in has_many

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Rolando A. (Guest)
on 2007-02-01 21:55
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.-
Zack C. (Guest)
on 2007-02-01 22:06
(Received via mailing list)
On 2/1/07, Rolando A. <removed_email_address@domain.invalid> 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...

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
Rolando A. (Guest)
on 2007-02-01 22:18
Zack C. wrote:
> Jamis just blogged about this recently:
>
> http://weblog.jamisbuck.org/2007/1/18/activerecord...


nice!!!
thanks a lot :-D

> 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.-
This topic is locked and can not be replied to.