I am trying to upgrade a rails 3.0 app to rails 4.0. One of the behaviour I noticed is the relationship between the models stopped working.
我正在尝试将rails 3.0应用程序升级到rails 4.0。我注意到的一个行为是模型之间的关系停止工作。
Assume 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 are able to 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 on Rails 4.0 I am getting Unknown column 'met_with_parent' in 'field list'
I believe Rails 4 is trying to be smart and not loading the entire given join tables.
这适用于Rails 3.0,但现在在Rails 4.0上,我在'字段列表'中获得了未知列'met_with_parent'我相信Rails 4正在尝试智能而不加载整个给定的连接表。
1 个解决方案
#1
3
I personally would recommend the following approach, using scopes:
我个人会推荐以下方法,使用范围:
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 the relationships AND filter when needed.
这允许您在需要时维护关系和过滤器。
#1
3
I personally would recommend the following approach, using scopes:
我个人会推荐以下方法,使用范围:
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 the relationships AND filter when needed.
这允许您在需要时维护关系和过滤器。