0
我不完全確定是否我的關係設置正確,但以下是我正在嘗試執行的操作。我正在嘗試將Grade
退回Student
的活動Enrollment
。無法訪問ActiveRecord上的相關屬性查詢
current_enrollments = self.enrollments.where('admission_date <= ? and withdraw_date is null or withdraw_date >= ?', Date.today, Date.today)
class SchoolYearGrade < ApplicationRecord
belongs_to :school_year
belongs_to :grade
has_many :enrollments
end
class Enrollment < ApplicationRecord
belongs_to :student
belongs_to :school_year_grade
end
class Grade < ApplicationRecord
has_many :school_years, through: :school_year_grades
has_many :school_year_grades
end
class Student < ApplicationRecord
has_many :enrollments
def get_current_grade
if self.enrollments.any?
current_enrollments = self.enrollments.where('admission_date <= ? and withdraw_date is null or withdraw_date >= ?', Date.today, Date.today)
if current_enrollments.count == 1
current_enrollments.first.school_year_grade.grade.title
else
...
end
else
...
end
end
end
當在Student
模型get_current_grade
方法調試,我嘗試訪問current_enrollments.first.school_year_grade.grade
並返回僅Nil
。然後我嘗試在current_enrollments
上添加.includes(:school_year_grade)
來查詢,但我仍然無法獲取任何內容。
什麼sql查詢被執行?結果是你期望它是什麼? – phoet