6

Próbuję uaktualnić aplikację rails 3.0 do rails 4.0. Jednym z zaobserwowanych przeze mnie zachowań jest relacja między modelami, które przestały działać.Rails 4 Has_many: Przez połączenie asocjacji z wybraniem

Załóżmy, że mamy następujące modele:

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 

Teraz jesteśmy w stanie to zrobić:

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 

Ten pracował dla Rails 3.0, ale teraz on Rails 4.0 Dostaję Unknown column 'met_with_parent' in 'field list' wierzę Rails 4 próbuje być sprytny i nie ładuje całej danej tabeli łączenia.

+0

Czy stara składnia działa w Rails 4.0? – lurker

+0

@mbratch no it does not work. Występuje ten sam problem. Ze starą składnią Railsy 4 będą rejestrować wiadomości deprecjacji. – Bill

+0

co będzie, jeśli spróbujesz wybrać nauczyciel_students.met_with_parent jako met_with_parent? – faron

Odpowiedz

3

Ja osobiście polecam następujące podejście, przy użyciu zakresów:

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 

Następnie można wykonać następujące czynności:

Teacher.first.students.met_with_parent 

To pozwala utrzymać relacje i filtr, gdy są potrzebne.

+0

gdzie ('teacher_students.met_with_student =?', True) - ugh. Po prostu nie. Wszystko, czego potrzebujesz, to "where (" teacher_students.met_with_student ")". Poza tym wygląda dobrze. –

Powiązane problemy