【问题标题】:Rails merge 2 query resultsRails 合并 2 个查询结果
【发布时间】:2014-03-18 11:26:08
【问题描述】:

我想显示 last_request >= 1.day.ago 的第一批用户,然后添加其余用户

  def self.default_scope
    where("last_request >= ?", 1.day.ago) + where("last_request < ? OR last_request is null", 1.day.ago)
  end

此代码引发了该错误:

undefined method `merge' for []:Array

我该怎么做?

更新

错误堆栈

NoMethodError - undefined method `merge' for #<Array:0xd16ba90>:
  activerecord (3.2.13) lib/active_record/relation.rb:503:in `with_default_scope'
  activerecord (3.2.13) lib/active_record/relation.rb:167:in `exec_queries'
  activerecord (3.2.13) lib/active_record/relation.rb:160:in `block in to_a'
  activerecord (3.2.13) lib/active_record/explain.rb:34:in `logging_query_plan'
  activerecord (3.2.13) lib/active_record/relation.rb:159:in `to_a'
  will_paginate (3.0.5) lib/will_paginate/active_record.rb:127:in `block in to_a'
  will_paginate (3.0.5) lib/will_paginate/collection.rb:96:in `create'
  will_paginate (3.0.5) lib/will_paginate/active_record.rb:126:in `to_a'

更新2

我正在使用 rails_admin,日期时间字段排序无法正常工作

1)升序

2)按降序排列

【问题讨论】:

  • 可以发布错误堆栈吗?
  • 我已经编辑了我的答案。看看吧。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

在您的特定情况下,您可以将范围与

   default_scope where('last_request >= :time OR (last_request < :time OR last_request IS NULL)', time: 1.day.ago).order('last_request DESC')

UPD 这不是 ActiveRecord 或 RailsAdmin 问题,更多信息

ORDER BY ASC with Nulls at the Bottom

Rails: Order with nulls last

【讨论】:

  • 抱歉,这样做与仅使用带有order 子句的default_scope 有什么区别?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
相关资源
最近更新 更多