rails 5 has_many through order on through table
<p>I want to order a <code>has_many through</code> relationship on a column in the through table</p>

<pre><code>class DoctorProfile
  has_many :doctor_specialties
  has_many :specialties, through: :doctor_specialties

class Specialty
  has_many :doctor_specialties
  has_many :doctor_profiles, through: :doctor_specialties

class DoctorSpecialty
  belongs_to :doctor_profile
  belongs_to :specialty
</code></pre>

<p>I'd like the doctor specialties to be ordered by the column <code>ordinal</code> on <code>DoctorSpecialty</code>. Specifically this error happens when using <code>includes</code></p>

<p><code>DoctorProfile.includes(:specialties).all</code></p>

<p>I've tried </p>

<p><code>has_many :specialties, -&gt; { order 'doctor_specialties.ordinal' }, through: :doctor_specialties</code></p>

<pre><code>DoctorProfile Load (0.6ms)  SELECT  "doctor_profiles".* FROM "doctor_profiles" ORDER BY "doctor_profiles"."id" ASC LIMIT $1  [["LIMIT", 1]]
  DoctorSpecialty Load (0.8ms)  SELECT "doctor_specialties".* FROM "doctor_specialties" WHERE "doctor_specialties"."doctor_profile_id" = 1
  Specialty Load (0.4ms)  SELECT "specialties".* FROM "specialties" WHERE "specialties"."id" = 69 ORDER BY doctor_specialties.ordinal
</code></pre>

<p>and receieve a missing FROM -clause error <code>PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "doctor_specialties"</code></p>

<p>How can I define the order on the through table so specialties are returning in ascending order?</p>

<p><strong>Note:</strong> </p>

<p>I was able to get this working by adding a <code>default_scope</code> to <code>DoctorSpecialty</code></p>

<p><code>default_scope { order('ordinal ASC') }</code></p>

<p>However, I'm still wondering if there is a way to do it on the <code>has_many through</code></p>