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
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
Not sure if this is what's causing your error but you haven't completed the has many through relationship on the Specialty side. Should be has_many :doctor_profiles, through: :doctor_specialties
Also for this line in DoctorProfiles has_many :specialties, through: doctor_specialties
, doctor_specialties
needs to be a symbol
As for the ordering I think you need to do a joins
instead of an includes
like DoctorProfile.joins(:doctor_specialties).order("doctor_specialties.ordinal ASC")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With