【发布时间】:2019-05-14 00:11:00
【问题描述】:
我正在尝试创建一个查询,该查询将根据关联表中的条件从一个表中返回不同的记录。
具体来说,有一个Act 模型,它有_many Events,当然还有“事件”属于Act 我想找到那些在特定日期没有Event 的Acts。
查询需要使用not 条件运行,否则结果将不会排除任何Act 记录。
我尝试了多种构造方法,包括跨类方法使用合并,但没有奏效。
#Act model
def self.busy_on(date)
joins(:event).merge.not(Event.busy_on(date))
end
#Event model
def self.busy_on(date)
where(date: date)
end
#Controller
Act.busy_on(params[:date])
上面给了我一个参数错误(期望 1 得到 0),但我不确定它是否正确。
【问题讨论】:
-
你可以使用 join & id is null 的组合,比如
joins(:event).where(events: { date: data, id: nil })。
标签: ruby-on-rails activerecord