我有以下设置:
class TeamEnrollment < ApplicationRecord
belongs_to :team
has_many :term_enrollments, through: :team
end
上面的代码工作正常。现在我需要将has_many行更改为如下所示:
has_many :term_enrollments,
-> {where("(term_enrollments.term_start_date <= ? AND term_enrollments.term_end_date >= ?) OR (term_enrollments.term_start_date >= ? AND term_enrollments.term_end_date > ?) OR (term_enrollments.term_start_date <= ? AND term_enrollments.term_end_date >= ?)", self.start_date, self.start_date, self.start_date, self.termination_date, self.termination_date, self.termination_date)}
, through: :team
从上面的代码中,如果我尝试TeamEnrollment.first.term_enrollments
,我会收到以下错误:
undefined method `start_date' for #<TermEnrollment::ActiveRecord_Relation:0x007ff706550550>
我已经使用上面第一个代码配置测试了where
子句,它运行正常。只有在has_many
子句中它才起作用。
我很确定它与has_many through
中的self的使用有关。我正在尝试引用TeamEnrollment的start_date。我该怎么做呢?
答案 0 :(得分:2)
关于范围的has_many
文档部分显示了以下示例:
has_many :posts, ->(blog) { where("max_post_length > ?", blog.max_post_length) }
该示例显示scope
可以接受一个参数,即在其上调用的记录