【问题标题】:Rails active record where chaining losing scope链接丢失范围的 Rails 活动记录
【发布时间】:2023-04-03 03:25:01
【问题描述】:

模型Food 具有范围expired

Food.rb

class Food < ApplicationRecord
  default_scope { where.not(status: 'DELETED') }
  scope :expired, -> { where('exp_date <= ?', DateTime.now) }
  belongs_to :user
end

在我的控制器中,我链接了按用户和状态过滤食物的条件:

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 范围(和条件)?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

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

    【讨论】:

    • 如果您需要进一步链接where(使用andor 运算符),是否会生成错误查询?
    • 这取决于您的链where 条件(将始终与AND 添加)和or 条件(OR 仅在事发前的最新条件)。
    • where 不希望有这样的范围 - 请您更详细地解释一下吗?或任何链接?
    • 看看Rails Guide about conditionswhere 接受字符串、数组或哈希,但不接受范围。
    • 当您仔细观察时,您会发现第 149 行的输出不是整个查询,缺少 where(user_id: user.id) 部分。这仅意味着 Rails 在内部触发了对添加范围的数据库请求,试图使其有意义,但实际上并未将返回值添加到条件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多