试图在rails 5中的has_many范围内引用self

时间:2017-09-04 16:10:50

标签: ruby-on-rails activerecord rails-activerecord ruby-on-rails-5 has-many-through

我有以下设置:

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。我该怎么做呢?

1 个答案:

答案 0 :(得分:2)

关于范围的has_many文档部分显示了以下示例:

has_many :posts, ->(blog) { where("max_post_length > ?", blog.max_post_length) }

该示例显示scope可以接受一个参数,即在其上调用的记录