【问题标题】:using Date.today in joins part of named scope使用 Date.today 加入命名范围的一部分
【发布时间】:2012-12-08 20:17:27
【问题描述】:

由于某种原因,当我在 where 中使用 Date 类时会被识别

scope :with_active_subthing, joins("left outer join thing_subthing on thing_subthing.patient_id = thing.id").where("thing_subthing.start_date <= ? AND ( thing_subthing.end_date > ? OR thing_subthing.end_date IS NULL ) ", Date.today, Date.today)

但是当我在连接中使用它时无法识别它

scope :with_active_subthing, joins("left outer join thing_subthing on thing_subthing.patient_id = thing.id AND (thing_subthing.start_date <= ? AND ( thing_subthing.end_date > ? OR thing_subthing.end_date IS NULL )) ", Date.today, Date.today)

我明白了:

RuntimeError: unknown class: Date

【问题讨论】:

    标签: sql ruby-on-rails arel


    【解决方案1】:

    如果您查看underlying code that builds the join portion,您可以看到它正在寻找特定的对象类型,而 Date 不是其中之一。该错误有点令人困惑,但它的意思是日期不能用作joins 的参数。您的问题并不清楚您为什么要这样做,但您绝对应该像在第一个示例中所做的那样同时使用连接和位置。

    这是导致问题的代码,因为它掉到了“raise”行:

    def build_joins(manager, joins)
      buckets = joins.group_by do |join|
        case join
        when String
          'string_join'
        when Hash, Symbol, Array
          'association_join'
        when ActiveRecord::Associations::JoinDependency::JoinAssociation
          'stashed_join'
        when Arel::Nodes::Join
          'join_node'
        else
          raise 'unknown class: %s' % join.class.name
        end
      end
    

    【讨论】:

    • accha。我懂了。我懂了。使用 where 子句的问题在于它有效地将其变成了一个内部连接我最终所做的只是在 SQL 中使用 now(),这使得它与数据库无关,但完成了。
    • 刚回到合适的电脑。所以我使用的代码基本上是:
    • scope :with_active_subthing, joins("left outer join thing_subthing on thing_subthing.thing_id = thing.id AND (thing_subthing.start_date now() OR thing_subthing.end_date IS NULL )) ") 所以无论如何,我想要连接本身的条件的原因是我希望查询返回每个事物,如果他们有一个活动的子事物(不是所有的子事物都是)返回他们的活动子事物(今天的活跃含义是在它们的开始日期和结束日期之间。)where 子句中的相同条件将排除所有没有子事物的事物。
    • @BrandonHamilton 目前还不清楚您的问题是什么。您最初的问题似乎是在问为什么您对无法识别的 Date 类有错误,我回答了。如果您对如何更好地进行查询还有其他问题,我会打开另一个问题并明确您的要求,以便获得更多答案。
    • 你完全正确。您按照要求回答了该帖子,这有助于找到实用的解决方案。关于查询的内容有点多余,感谢您的帮助。
    猜你喜欢
    • 2014-07-03
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多