首页 > 解决方案 > 链接丢失范围的 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 行失去范围(和条件)?

标签: ruby-on-railsrubyactiverecord

解决方案


它被忽略,因为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)

推荐阅读