rails 5 has_many through order on through table
activerecord, ruby-on-rails
Solution
I was able to get it working using
class DoctorProfile
has_many :specialties, -> { order 'doctor_specialties.ordinal' }, through: :doctor_specialties
end
class DoctorSpecialty < ApplicationRecord
belongs_to :doctor_profile
belongs_to :specialty
default_scope { order('ordinal ASC') }
end
Problem
I want to order a `has_many through` relationship on a column in the through table ``` 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 ``` I'd like the doctor specialties to be ordered by the column `ordinal` on `DoctorSpecialty`. Specifically this error happens when using `includes` `DoctorProfile.includes(:specialties).all` I've tried `has_many :specialties, -> { order 'doctor_specialties.ordinal' }, through: :doctor_specialties` ``` 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 ``` and receieve a missing FROM -clause error `PG::UndefinedTable: ERROR: missing FROM-clause entry for table "doctor_specialties"` How can I define the order on the through table so specialties are returning in ascending order? Note: I was able to get this working by adding a `default_scope` to `DoctorSpecialty` `default_scope { order('ordinal ASC') }` However, I'm still wondering if there is a way to do it on the `has_many through`