Topic: Ordering models based on has_one associations?

Hi, I'm new to Rails, and I would like to do something that I hope is fairly easy.
I have two models with a one to one relationship

class Host < ActiveRecord::Base
  has_many :connections, :order => 'time DESC'
  has_one :recent, =>class_name =>'Connection', :order => 'time DESC'
end

class Connection < ActiveRecord::Base
  belongs_to :host
end

class CreateConnections < ActiveRecord::Migration
  def self.up
    create_table :connections do |t|
      t.column :ipaddr, :string
      t.column :time, :datetime
      t.column :host_id, :integer
    end
  end

  def self.down
    drop_table :connections
  end
end


Now, in my HostController, I want to list the hosts in order of the time attribute for it's most connection.
How do I do this?

I know that if I had a time attribute in the host model itself, I could just do

Host.find(:all, :order => 'time DESC')

But I dont' know if or how this applies with the has_one option. Anyone have any suggestions?

Last edited by folkstone (2006-11-22 15:30:16)

Re: Ordering models based on has_one associations?

I don't if this will work, but it's worth a try:

@hosts = Host.find(:all, :include => :connections, :order => 'connections.time DESC')

Railscasts - Free Ruby on Rails Screencasts