Reputation: 4677
I have the following setup:
class TeamEnrollment < ApplicationRecord
belongs_to :team
has_many :term_enrollments, through: :team
end
The above code works fine. Now I need to change the has_many line to look like this:
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
From the code above, I get the following error if I try to do TeamEnrollment.first.term_enrollments
:
undefined method `start_date' for #<TermEnrollment::ActiveRecord_Relation:0x007ff706550550>
I have tested the where
clause with the first configuration of code above and it works fine. It's only when in the has_many
clause that it does not work.
I'm pretty sure it has to do with the use of self inside of the has_many through
. I'm trying to refer to the TeamEnrollment's start_date. How Do I do this?
Upvotes: 2
Views: 1907
Reputation: 11035
The has_many
documentation section about scopes shows the following example:
has_many :posts, ->(blog) { where("max_post_length > ?", blog.max_post_length) }
That example shows that the scope
can take a parameter, which is the record it's being called on
Upvotes: 5