【发布时间】:2017-07-11 19:37:22
【问题描述】:
我有一个这样构建的查询:
@events = current_organization.events.order(started_at: :asc)
我想查询所有status 不是"canceled" 的事件。但是,当我使用这样的查询时:
current_organization.events.order(started_at: :asc).where.not(status: "canceled")
它什么也不返回。但是,只是为了实验,我尝试了:
@events = current_organization.events.where(status: "canceled")
它成功返回了取消的事件。由于某种原因,反向不起作用。有什么原因吗?
编辑:我能找到的唯一解决方法就是使用where(status: nil),但这真的很不直观。
【问题讨论】:
-
尝试检查#to_sql 输出。这有助于调试 sql 语句 current_organization.events.order(started_at: :asc).where.not(status: "canceled").to_sql
-
您的事件模型上是否设置了
default_scope? -
@MickeySheu,这里是不同的输出
@events = current_organization.events.order(started_at: :asc).where(status: "canceled").to_sql=> "SELECT \"events\".* FROM \"events\" WHERE \"events\".\"organization_id\" = 1 AND \"events\".\"status\" = 'canceled' ORDER BY \"events\".\"started_at\" ASC”@events = current_organization.events.order(started_at: :asc).where.not(status: "canceled").to_sql=> “SELECT \"events\".* FROM \"events\" WHERE \"events\".\"organization_id\" = 1 AND (\"events\".\"status\" != 'canceled') ORDER BY \"events\".\"started_at\" ASC” -
@mysmallidea,我的事件模型上没有设置默认范围
-
您为什么希望您的
where.not查询能找到任何东西?您确定该组织有未取消的活动吗?
标签: ruby-on-rails ruby activerecord rails-activerecord ruby-on-rails-5