6

Sto provando ad aggiornare un'applicazione di rails 3.0 alle guide 4.0. Uno dei comportamenti che ho notato è che la relazione tra i modelli ha smesso di funzionare.Rails 4 Has_many: attraverso join join con select

Supponiamo di avere i seguenti modelli:

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 

ora siamo in grado di fare:

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 

Questo ha funzionato per Rails 3.0, ma ora on Rails 4.0 che sto ottenendo Unknown column 'met_with_parent' in 'field list' credo Rails 4 sta cercando di essere intelligente e non sta caricando tutte le tabelle di join date.

+0

La vecchia sintassi funziona in Rails 4.0? – lurker

+0

@mbratch no non funziona. Lo stesso problema si verifica. Con la vecchia sintassi Rails 4 registrerà una serie di messaggi di deprecazione. – Bill

+0

cosa succederà se proverai select teacher_students.met_with_parent come met_with_parent? – faron

risposta

3

io personalmente consiglierei il seguente approccio, utilizzando gli ambiti:

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 

Quindi è possibile effettuare le seguenti operazioni:

Teacher.first.students.met_with_parent 

Questo consente di mantenere le relazioni e il filtro quando necessario.

+0

where ('teacher_students.met_with_student =?', True) - ugh. Solo, no. Tutto ciò che serve è "where ('teacher_students.met_with_student')". A parte questo, sembra buono. –

Problemi correlati