Rails 4 Has_many: By Combining a Connection with a Selection

I am trying to upgrade a rails 3.0 application to rails 4.0. One of the comments that I noticed is the relationship between models that have stopped working.

Suppose we have the following models:

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 

Now we can do:

 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 

This worked for Rails 3.0, but now in Rails 4.0 I get an Unknown column 'met_with_parent' in 'field list' . I believe Rails 4 is trying to be smart and not load all of the specified connection tables.

+6
source share
1 answer

I personally would recommend the following approach using areas:

 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 

Then you can do the following:

 Teacher.first.students.met_with_parent 

This allows you to maintain relationships AND filter when necessary.

+3
source

Source: https://habr.com/ru/post/948088/


All Articles