Rails 链接丢失范围的活动记录
Rails active record where chaining losing scope
模型 Food
具有范围 expired
:
Food.rb
class Food < ApplicationRecord
default_scope { where.not(status: 'DELETED') }
scope :expired, -> { where('exp_date <= ?', DateTime.now) }
belongs_to :user
end
在我的控制器中,我链接 where 条件以按用户和状态过滤食物:
query_type.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
为什么活动记录查询在第 157 行丢失 expired
范围(和条件)?
它被忽略了,因为 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)
模型 Food
具有范围 expired
:
Food.rb
class Food < ApplicationRecord
default_scope { where.not(status: 'DELETED') }
scope :expired, -> { where('exp_date <= ?', DateTime.now) }
belongs_to :user
end
在我的控制器中,我链接 where 条件以按用户和状态过滤食物:
query_type.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
为什么活动记录查询在第 157 行丢失 expired
范围(和条件)?
它被忽略了,因为 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)