Rails has_many通过where子句

时间:2018-05-07 14:49:59

标签: ruby-on-rails

我需要帮助来实现目标。

我的分析has_many :klasses, through: :subjects是否可能,但是使用来自连接表AnalysisSubject的属性进行过滤?或者我的模特应该有所不同?

class Analysis
  has_many :analysis_subjects, dependent: :destroy
  has_many :subjects, through: :analysis_subjects
  has_many :klasses, -> { where(year: ??????, semester: ??????), through: :subjects
end

class AnalysisSubject
  belongs_to :analysis
  belongs_to :subject

  # There are year:integer and semester:integer attributes
  # I want to use those attributes in my where clause for analysis.klasses
end

class Subject
  has_many :klasses
  has_many :analysis_subjects
  has_many :analyses, through: :analysis_subjects
end

class Klass
  belongs_to :subject
end

如果重要的话,我正在使用Rails 5。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

是的,但您应该以不同的方式支付费用:您必须在where中声明has_many :filtered_analysis_subjects

class Analysis
  has_many :filtered_analisys_subjects, -> { where(year: x, semester: y }, foreign_key: "analysis_id", class_name: "AnalysisSubject", dependent: :destroy 
  has_many :subjects, through: :filtered_analysis_subjects
  has_many :klasses, through: :subjects