Forum: Ruby on Rails easiest way to order by field in joined table

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.
glenn (Guest)
on 2007-04-10 12:14
(Received via mailing list)
hey there -

given a simple table like this:
orders.id
orders.client_id
orders.supplier_id
orders.date_ordered

I create and index view that has in it something like this:
<td><%= @orders.id %></td>
<td><%= @orders.client_name %></td>
<td><%= @orders.supplier_name %></td>
<td><%= @orders.date_ordered %></td>

Ultimately, I'm wanting to provide an 'index' page, that can be
resorted on a column of the users choice (i.e.id, client_name,
suplier_name, date_ordered)

So thats obviously easy for date_ordered, and id
i.e.
Order.find(:all, :order=>"date_ordered") for example


BUT to sort by the the client name or supplier name, data which are
obviously in a joined table - it gets curlier. Coming from an sql
background, i'd assume it should be very very simple, but activerecord
seems to obscure something simple and make it a guessing game of
syntax - ok - probably not a fair comment... can someone set me
straight on this and show me how ?

thanks

glenn
Thorsten (Guest)
on 2007-04-10 12:53
(Received via mailing list)
should just work like:

@orders = Order.find :all, :include => :suppliers, :order =>
"supplier.name DESC"

the value to pass to :order is just an SQL Fragment.
in SQL you would do "ORDER BY supplier.name DESC"
in AR you do :order => "supplier.name DESC"
glenn (Guest)
on 2007-04-10 14:23
(Received via mailing list)
On Apr 10, 6:52 pm, "Thorsten" <removed_email_address@domain.invalid> wrote:
> should just work like:
>
> @orders = Order.find :all, :include => :suppliers, :order =>
> "supplier.name DESC"
>
> the value to pass to :order is just an SQL Fragment.
> in SQL you would do "ORDER BY supplier.name DESC"
> in AR you do :order => "supplier.name DESC"
>

Beautiful... thanks - like I said, prob wasnt a fair comment ;-)
Ball, Donald A Jr (Library) (Guest)
on 2007-04-10 23:02
(Received via mailing list)
> <td><%= @orders.date_ordered %></td>
> which are obviously in a joined table - it gets curlier.
> Coming from an sql background, i'd assume it should be very
> very simple, but activerecord seems to obscure something
> simple and make it a guessing game of syntax - ok - probably
> not a fair comment... can someone set me straight on this and
> show me how ?

Try...

Order.find(:all, {:include=>[:client, :supplier],
:order=>'clients.name'})

- donald
This topic is locked and can not be replied to.