2

I have two models:

class Doctor < ActiveRecord::Base
  has_and_belongs_to_many :branches
end

class Branch < ActiveRecord::Base
  has_and_belongs_to_many :doctors
end                             

I want to order the list of doctors(index action) by the branch name either ASC or Desc. How can I do this?

4

1 回答 1

1

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).

于 2013-01-30T21:24:48.240 回答