尝试在 Rails 3 中创建具有 habtm 关系的范围

2024-02-07

我正在尝试对活动记录进行基本搜索,但由于 has_and_belongs_to_many 关系而遇到麻烦。以下是我创建的记录和范围。

Class Section << ActiveRecord::Base
  has_and_belongs_to_many :teachers
  attr_accessible :department, :class_size

  scope :department_scope, lambda { |dept| where("department = ?", dept) }
  scope :teacher_fname_scope, lambda { |n| joins(:teachers) & Teacher.has_first_name(n) }
end


Class Teacher << ActiveRecord::Base
  has_and_belongs_to_many :sections
  attr_accessible :first_name, :last_name

  scope :has_first_name, lambda { |fname| where("first_name = ?", fname) }
end

在 Rails 3.2 中,我正在为我的部分模型创建基本搜索。假设我想搜索具有给定名字的教师的所有部分。

我已经使用上面的范围进行了尝试,但我从 *Section.teacher_fname_scope* 返回的只是一个空数组。

(我实际上将有多个字段,让用户也搜索部门字段和类大小,所以我可能会创建多个范围并最终将它们链接在一起,例如上面的搜索也受到部门和类大小的限制,但我的理解是范围是正交的,所以这对上面的问题并不重要。)

谢谢你的帮助。


看起来获胜范围是:

Class Section << ActiveRecord::Base
  scope :teacher_fname_scope, lambda { |n| joins(:teachers).("teachers.first_name = ?", n) }
end

这是有道理的,但我不明白为什么原版不起作用,考虑到 Ryan Bates 在http://railscasts.com/episodes/215-advanced-queries-in-rails-3?view=asciicast http://railscasts.com/episodes/215-advanced-queries-in-rails-3?view=asciicast

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试在 Rails 3 中创建具有 habtm 关系的范围 的相关文章

随机推荐