Mateusz Urbański
Mateusz Urbański

Reputation: 7862

Ruby on Rails deep order

I have a problem with deep sorting in Ruby on Rails. I have the following associations.

class Device < ActiveRecord::Base
  belongs_to :station
end

class Station < ActiveRecord::Base
  has_one :address, dependent: :destroy
  has_many :devices
end

class Address < ActiveRecord::Base
  belongs_to :station

  validates :street, :suburb, :state, :postcode, :country, presence: true
end

And now I want to order all devices by its station adress street field. Is there any way to do this deep merge?

Upvotes: 0

Views: 100

Answers (1)

SHS
SHS

Reputation: 7744

Yes, there is a way.

Given that the Address model's table's name is addresses, that all devices have a station, and that all stations have one address, you could use the following:

Device.
joins(station: :address).
order("addresses.street ASC") # you can change ASC to DESC

The above joins applies inner joins. In case there are 'missing' associations e.g. a station doesn't have an address, then you will need to use outer joins, either explicitly with raw SQL or using the includes method.

Upvotes: 1

Related Questions