Duncan Malashock
Duncan Malashock

Reputation: 786

ActiveRecord: Sort records by attributes on their relations

I have Candidates which belong to a District. Districts can be of district_type "Assembly" or "Senate", and Candidates can be incumbent (true/false). I'm trying to sort Candidates by the type of District they belong to:

assembly_nonincumbents = Candidate.where(:incumbent => true, :district.district_type => 'Assembly').order('LOWER(last_name) ASC')

But this is giving me an error: undefined method `district_type' for :district:Symbol

Upvotes: 0

Views: 82

Answers (1)

Carl Zulauf
Carl Zulauf

Reputation: 39558

This solution will filter candidates by district using a sub-query. I think that's what you're trying to do.

assembly_incumbents = Candidate.where(
  incumbent: true,
  district_id: District.where(district_type: "Assembly")
).order("LOWER(last_name)")

UPDATE

If you want your result set ordered by a column in your districts table you'd need to do a join, which would look something like this:

Candidate.joins(:district).
          where(incumbent: true).
          where("districts.district_type = ?", "Assembly").
          order("districts.district_number, LOWER(last_name)")

Something like that should work and would order the results first by district_number, then by name (so if district 37 has 4 candidates, they will all come after district 36 candidates but will be ordered by name within the list of district 37 candidates).

Upvotes: 1

Related Questions