2016-08-13 55 views
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)來查詢,但我仍然無法獲取任何內容。

+0

什麼sql查詢被執行?結果是你期望它是什麼? – phoet

回答

0

我很尷尬;在進一步的檢查中,我有一些無效的數據庫值指向不存在記錄。猜測我需要一些限制!