rails 5 has_many贯穿整个表

时间:2016-10-25 18:42:28

标签: ruby-on-rails activerecord

我想在直通表

中的列上订购has_many through关系
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

我希望ordinal上的专栏DoctorSpecialty订购专科医生。特别是在使用includes

时会发生此错误

DoctorProfile.includes(:specialties).all

我已经尝试了

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

并收到遗漏的FROM -clause错误PG::UndefinedTable: ERROR: missing FROM-clause entry for table "doctor_specialties"

如何定义直通表上的顺序,以便专业按升序返回?

注意:

我能够通过向default_scope

添加DoctorSpecialty来实现这一目标

default_scope { order('ordinal ASC') }

但是,我仍然想知道是否有办法在has_many through

上执行此操作

2 个答案:

答案 0 :(得分:1)

不确定这是否导致您的错误,但您还没有完成在专业方面有很多关系。应为has_many :doctor_profiles, through: :doctor_specialties

对于DoctorProfiles has_many :specialties, through: doctor_specialties中的这一行,doctor_specialties需要是一个符号

关于订购,我认为你需要做joins而不是includes

喜欢DoctorProfile.joins(:doctor_specialties).order("doctor_specialties.ordinal ASC")

答案 1 :(得分:0)

我能够使用它来工作

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
相关问题