6

我正在嘗試將rails 3.0應用升級到rails 4.0。我注意到的一種行爲是模型之間的關係停止工作。Rails 4 Has_many:通過加入關聯選擇

假設我們有以下型號:

class Student < ActiveRecord::Base 
    has_many :teacher_students 
    has_many :teachers, :through => :teacher_students, :select => 'teacher_students.met_with_parent, teachers.*' 

    # The Rails 4 syntax 
    has_many :teachers, -> { select('teacher_students.met_with_parent, teachers.*') }, :through => :teacher_students 

end 

class Teacher < ActiveRecord::Base 
    has_many :teacher_students 
    has_many :students, :through => :teacher_students, :select => 'teacher_students.met_with_parent, students.*' 
end 

class TeacherStudent < ActiveRecord::Base 
    belongs_to :teacher 
    belongs_to :student 
    # Boolean column called 'met_with_parent' 
end 

現在,我們能夠做到:

teacher = Teacher.first 
students = teacher.students 
students.each do |student| 
    student.met_with_parent  # Accessing this column which is part of the join table 
end 

這個工作對Rails的3.0,但現在on Rails的4.0我收到Unknown column 'met_with_parent' in 'field list'我相信Rails的4試圖變得聰明,而不是加載整個給定的連接表。

+0

舊的語法在Rails 4.0中工作嗎? – lurker

+0

@mbratch不,它不起作用。同樣的問題發生。使用舊的語法Rails 4會記錄一堆棄用消息。 – Bill

+0

如果您嘗試選擇teacher_students.met_with_parent作爲met_with_parent會怎麼樣? – faron

回答

3

我個人推薦以下方法,使用範圍:

class Student < ActiveRecord::Base 
    has_many :teacher_students 
    has_many :teachers, :through => :teacher_students 
end 

class Teacher < ActiveRecord::Base 
    has_many :teacher_students 
    has_many :students, :through => :teacher_students 

    scope :met_with_parent, -> { joins(:teacher_students).where('teacher_students.met_with_student = ?', true) } 
end 

class TeacherStudent < ActiveRecord::Base 
    belongs_to :teacher 
    belongs_to :student 
end 

然後你就可以做到以下幾點:

Teacher.first.students.met_with_parent 

這使您可以在需要時維持關係和過濾器。

+0

where('teacher_students.met_with_student =?',true) - 呃。就是不行。所有你需要的是「where('teacher_students.met_with_student')」。除此之外,看起來不錯。 –