ruby-on-rails - 链接丢失范围的 Rails 活动记录
问题描述
模型Food
有范围expired
:
食物.rb
class Food < ApplicationRecord
default_scope { where.not(status: 'DELETED') }
scope :expired, -> { where('exp_date <= ?', DateTime.now) }
belongs_to :user
end
在我的控制器中,我链接了按用户和状态过滤食物的条件:
查询类型.rb
def my_listing_connection(filter)
user = context[:current_user]
scope = Food.where(user_id: user.id)
if filter[:status] == 'ARCHIVED'
# Line 149
scope = scope.where(
Food.expired.or(Food.where(status: 'COMPLETED'))
)
else
scope = scope.where(status: filter[:status])
end
scope.order(created_at: :desc, id: :desc)
# LINE 157
scope
end
这是rails日志:
Food Load (2.7ms) SELECT `foods`.* FROM `foods` WHERE `foods`.`status` !=
'DELETED'
AND ((exp_date <= '2020-07-02 09:58:16.435609') OR `foods`.`status` = 'COMPLETED')
↳ app/graphql/types/query_type.rb:149
Food Load (1.6ms) SELECT `foods`.* FROM `foods` WHERE `foods`.`status` != 'DELETED'
AND `foods`.`user_id` = 1 ORDER BY `foods`.`created_at` DESC, `foods`.`id` DESC
↳ app/graphql/types/query_type.rb:157
为什么活动记录查询expired
在第 157 行失去范围(和条件)?
解决方案
它被忽略,因为where
不期望这样的范围。但你可以merge
改用。代替
scope = scope.where(
Food.expired.or(Food.where(status: 'COMPLETED'))
)
和
scope = scope.merge(Food.expired)
.or(Food.where(status: 'COMPLETED'))
或者
scope = scope.where(status: 'COMPLETED').or(Food.expired)
推荐阅读
- redis - 使用带有 Redis 的 spring-session 时出现 @ConfigurationProperties 问题
- android - 如何使用 Android CameraX API 缩放相机?
- r - 如何在两个特定值之间重新编码一系列行
- c# - 无法从 azure vm 机器打开 selenium chrome 驱动程序到我的客户端机器?这甚至可能吗?
- ruby-on-rails - Rails 从早上 9 点开始获取过去 24 小时的数据
- python - 如何在 python 烧瓶中使用 Graylog
- javascript - 下拉菜单不显示在导航栏中
- jquery - 当flask wtforms抛出错误时,如何更改Bootstrap表单输入字段的边框颜色?
- javascript - 如何修复“TypeError:fsevents 不是构造函数”反应错误
- javascript - 如何在 javascript 中创建 ORC(或 parquet)文件?