2017-10-22 13 views
0

を使用してのActiveRecordを使用してクエリを書く、私は次のように与えられたSTUDENT_IDからSectionsのリストを返すアクティブレコードクエリ記述しようとしています:複数の関係に、下記の関係を考えると

def self.student_courses(student_id) 
    Section 
     .where(enrollment: Enrollment 
     .where(student: Student.find_by(student_id: student_id))) 
    end 

が、これはスローをエラー:SQLException: no such column: sections.enrollment:

私が理解しているように、セクションにその名前の列はありません。特定の生徒のためにSections?のリストを返すためにクエリを書くべきですか?

ERD

class Section < ApplicationRecord 
    has_many :enrollments 
    has_many :students, through: :enrollments 
    belongs_to :course 

入学

class Enrollment < ApplicationRecord 
    belongs_to :section 
    belongs_to :student 
end 

学生

class Student < ApplicationRecord 
    has_many :enrollments 
    has_many :sections, through: :enrollments 
end 

答えて

1

Railsのプライマリキー列のプレフィックスを付けないでください。それらをRailsの規約であるidと命名してください。一般的な接頭辞ではあいまいな識別子を持つ厄介なSQLを書くのは問題ではありません。

Railsのすべて設定より規約及びその他すべての関連付け

それレガシーアプリケーションの場合はcan be doneがいない間に主キー列を指定する必要があります非従来型のカラム名を使用してについてですあなたの人生を困難にし、新しいコードを実行することによって愚かなアプリにしましょう。

あなたは関連付けられたレコードにアクセスするのPKの名前を変更することで問題を整流した後のように簡単です:

Section.joins(:students).where(students: { id: x }) 
# or 
Section.joins(:enrollment).where(enrollment: { student_id: x }) 
# or 
student = Student.eager_load(:sections).find(x) 
student.sections