gpt4 book ai didi

ruby-on-rails - 在范围内使用 OR 进行查询

转载 作者:行者123 更新时间:2023-12-03 07:08:38 24 4
gpt4 key购买 nike

在 Rails3 中我有:

Class Teacher
# active :boolean
has_and_belongs_to_many :subjects

Class Subject
# active :boolean
has_and_belongs_to_many :teachers

我正在尝试构建一个返回所有 Teachers 的 Teacher 范围。那是active或与 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})

最佳答案

Squeel 可以拯救你。更多详情here .

使用它,您可以定义如下内容:

class Teacher
...
scope :active_teachers, joins{subjects}.where {(active == true) | (subjects.active == true)}
...
end

关于ruby-on-rails - 在范围内使用 OR 进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16381619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com