【问题标题】:Rails 4 Has_many :through join association with selectRails 4 Has_many:通过加入关联与选择
【发布时间】:2013-06-25 17:46:02
【问题描述】:

我正在尝试将 rails 3.0 应用程序升级到 rails 4.0。我注意到的一种行为是模型之间的关系停止工作。

假设我们有以下模型:

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,但现在在 Rails 4.0 上我得到了Unknown column 'met_with_parent' in 'field list' 我相信 Rails 4 正在努力变得聪明,而不是加载整个给定的连接表。

【问题讨论】:

  • 旧语法在 Rails 4.0 中有效吗?
  • @mbratch 不,它不起作用。出现同样的问题。使用旧语法 Rails 4 会记录一堆弃用消息。
  • 如果您尝试选择teacher_students.met_with_parent 作为met_with_parent 会怎样?

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-4


【解决方案1】:

我个人会推荐以下方法,使用范围:

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

这允许您在需要时维护关系和过滤。

【讨论】:

  • where('teacher_students.met_with_student = ?', true) - 呃。就是不行。你所需要的只是“哪里('teacher_students.met_with_student')”。除此之外,看起来不错。
猜你喜欢
  • 2016-03-20
  • 2015-11-16
  • 2014-12-16
  • 2013-11-24
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多