【问题标题】:Ruby On Rails Active Record - Where Condition AND This Condition or That ConditionRuby On Rails Active Record - Where Condition AND This Condition or That Condition
【发布时间】:2021-06-10 04:35:41
【问题描述】:

我有一个简单的时间跟踪器,只是尝试编写一个满足以下条件的查询并使用以下内容提取所有记录:user_id = 6 AND(is_paused 为 true 或 manual_input_hours 为 nil)。

根据我尝试的结构如下

Timerecord.where(user_id: 6).where(Timerecord.where(is_paused: true).or(Timerecord.where.not(manual_input_hours: 0)))

但它不起作用,出现以下错误:不支持的参数类型:#Timerecord::ActiveRecord_Relation:0x000056546f549358 (Timerecord::ActiveRecord_Relation) (ArgumentError)

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6


    【解决方案1】:

    你的 OR 部分是正确的,你只需要将它与用户查询结合起来。您可以使用 merge 方法来获得 AND 行为:

    records_for_user = Timerecord.where(user_id: 6)
    paused           = Timerecord.where(is_paused: true)
    has_manual_input = Timerecord.where.not(manual_input_hours: 0)
    
    # records_for_user AND (paused OR has_manual_input)
    records_for_user.merge(paused.or(has_manual_input))
    

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2022-12-02
      • 2019-12-25
      • 2011-08-28
      相关资源
      最近更新 更多