Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails merge 2 query results

I want to show first users with last_request >= 1.day.ago and then add the rest users

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

This code raises that error:

undefined method `merge' for []:Array

How could I do that?

UPDATE

Error stack

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

I am using rails_admin, datetime field ordering is not working correctly

1)Order by ascending

enter image description here

2)Order by descending

enter image description here

like image 210
Aydar Omurbekov Avatar asked Dec 30 '25 14:12

Aydar Omurbekov


1 Answers

In your particular case you can combine scopes to one with

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

UPD That is not ActiveRecord or RailsAdmin issue, more info

ORDER BY ASC with Nulls at the Bottom

Rails: Order with nulls last

like image 67
Fivell Avatar answered Jan 02 '26 03:01

Fivell