Easiest way to order by field in joined table


#1

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:

<%= @orders.id %> <%= @orders.client_name %> <%= @orders.supplier_name %> <%= @orders.date_ordered %>

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


#2

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”


#3

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 :wink:


#4
<%= @orders.date_ordered %> 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