【发布时间】:2023-04-08 01:58:01
【问题描述】:
在 Rails3 中我有:
Class Teacher
# active :boolean
has_and_belongs_to_many :subjects
Class Subject
# active :boolean
has_and_belongs_to_many :teachers
我正在尝试构建一个 Teacher 范围,它返回所有 active 的 Teachers 或与 Subject 相关联的 active。
这些作用域单独工作,但是如何将它们作为一个单个作用域与 OR 结合起来?
scope :active_teachers, where(active: true)
scope :more_active_teachers, joins(:subjects).where(:subjects => {active: true})
我试过这个没有成功:
scope :active_teachers, where(active: true).or(joins(:subjects)
.where(:subjects => {active: true}))
更新:
我以为我有一个解决方案,但这不再是延迟加载,而是两次访问数据库并且——最重要的是——返回一个数组而不是一个 AR 对象!
scope :active_teachers, where(active: true) |
joins(:subjects).where(:subjects => {active: true})
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord