I don't believe the HABTM association works differently than any other one-to-many would in this context, so you'd use select()
, group()
, and order()
, probably something like this:
@doctors = Doctor.joins(:branches).group('doctors.id').order('max(branches.name)')
Naturally, you'll need to choose how to aggregate this - a Doctor can have many Branches, so you'll have to specify which name to use in the ordering - max()
may not be the correct aggregate function for your needs.
Note that this will exclude any Doctor models that don't have any associated Branches, since the default for joins
is to use an inner join. If you don't want to do that, you'll probably have to write the joins
out manually, so that it uses left joins instead of inner joins, like so:
joins('left join branches_doctors on doctors.id = branches_doctors.doctor_id left join branches on branch.id = branches_doctors.branch_id')
The default name for a HABTM join table is the plural form of both models in alphabetical order (hence branches_doctors
, rather than doctors_branches
).