A
A
Andrey Demidenko2015-03-31 09:28:20
Ruby on Rails
Andrey Demidenko, 2015-03-31 09:28:20

How to sort related tables correctly?

If I want to sort all contracts by department name, am I doing the right thing?
@contracts = Contract.includes(:department).order('departments.name asc')

class Department < ActiveRecord::Base
  has_many :contracts
end

class Contract < ActiveRecord::Base
  belongs_to :department	
end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniel254, 2015-03-31
@Dem1

Contract.joins(:department).order('departments.name asc')

But if my memory serves me right, then rails will process your request using INNER JOIN and sort it correctly.

Z
zion5un, 2015-03-31
@zion5un

fix the endings a bit
@contracts = Contract.includes(:department s ).order('departments.name asc')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question