ab217
ab217

Reputation: 17160

Default Scope - Sort model by 2 columns where one is an association - Rails

I have two classes Building and Room. I want to sort my Room model by the building's name attribute and then by the room's room_number attribute. This is essentially what I want to do:

class Room
  belongs_to :building

  default_scope :order => 'building.name, room_number' # Doesn't work.
end

I just don't know how to get the association to work. Is there a way to do this in Rails?

Upvotes: 0

Views: 998

Answers (1)

Nick Colgan
Nick Colgan

Reputation: 5508

You have to JOIN the buildings table before you can reference in the order condition.

default_scope :joins => :building, :order => 'buildings.name, room_number'

Upvotes: 5

Related Questions