【发布时间】:2011-09-18 07:00:16
【问题描述】:
我正在尝试通过四层(哎呀!)关联进行查询。关联如下:
(编辑:添加了关联细节,我在源代码中有它们但没有在此处包含它们)
Provider
has_many :specialties, :through => :provider_specialties
has_many :provider_specialties, :through => :provider_licenses
has_many :provider_licenses
ProviderLicense
belongs_to :provider
has_many :specialties, :through => :provider_specialties
has_many :provider_specialties
#linking model between ProviderLicense and Specialty
ProviderSpecialty
belongs_to :provider_license
belongs_to :specialty
Specialty
has_many :provider_specialties
我的出发点是 Ryan Bates 的 RailsCast。我已经成功地搜索了一层深的关联对象,但是这一层正在杀死我。
providers = Provider.includes([:provider_languages, { :provider_licenses => :provider_specialties }]).where(conditions)
def specialties_and_conditions
["providers_specialties.specialty_id = ?", specialty_id] unless specialty_id.blank?
end
(编辑:下面的工作查询和连接)
Provider.joins([:specialties => { :provider_licenses => :provider_specialties }]).where(conditions)
def specialties_and_conditions
["specialty_id = ?", specialty_id] unless specialty_id.blank?
end
我不太明白“包含”方法的工作原理。我正在尝试使用上面的代码在 ProviderSpecialty(链接)关系中搜索 special_id,但没有成功。任何帮助将不胜感激!谢谢!
【问题讨论】:
-
您能添加一个查询示例吗?我在关注这里的关联时遇到了麻烦。如果
ProviderSpecialty是一个连接模型,则您缺少has_many :through关联。
标签: sql ruby-on-rails include