Rails合并2个查询结果

时间:2014-03-18 11:26:09

标签: ruby-on-rails ruby activerecord

我想向第一个用户显示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'

UPDATE2

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

1)按升序排序

enter image description here

2)按降序排序

enter image description here

1 个答案:

答案 0 :(得分:3)

在您的特定情况下,您可以将范围与一个范围组合  

   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