Sort array returned by ActiveRecord by date (or any other column)
Ruby includes support for sorting out of the box.
sorted = @records.sort_by &:created_at
However, this doesn't appear to have much to do with display and probably belongs in the controller.
Sort 2 Activerecords by date - when date fields are a different name in RAILS
You can use the Ruby method sort_by
:
@spotlight = @spotlight.sort_by do |record|
if record.respond_to?(:release_date)
record.release_date
else
record.publish_at
end
end
# sort by date ASC, you can use reverse! to change to order to DESC
# @sportlight.reverse!
This code implies that every @spotlight
records will always return a date from calling either release_date
or publish_at
(Ruby can't compare nil with Date). Also, this could be expensive in performances if you have a lot of records in @spotlight
(like a hundred of records or more).
Activerecord sort by column and then created_at?
Firstly, just define a scope like this:
class Item < ActiveRecord::Base
scope :ordered, -> {
joins("LEFT OUTER JOIN ( SELECT id, created_at, status
FROM items
WHERE items.status = 'outstanding'
) AS temp ON temp.id = items.id AND temp.status = items.status"
).order('temp.created_at NULLS LAST, items.status, items.created_at')
}
end
The magic is: (expect your table name is items
)
- Left join
items
withoutstanding items
. Sotemp.id
andtemp.created_at
will beNULL
for items which don't have statusoutstanding
- Order by
temp.created_at NULLS LAST
first, so theitems
which don't have statusoutstanding
will be ordered last. Then just do order by normally:items.status
(this makes the same statuses will be closed by each other) anditems.created_at
You can run the query with scope ordered
for 15 items only:
Item.ordered.limit(15)
Ruby on Rails: how to sort data in an array of active record objects right before iterating?
@menu_bar.link_pages.sort_by { |e| e.sequence }.each do |lp|
. . .
activerecord sort query codeigniter
if you have a table like
id | name | date | logic_erased
1 juan 2016-06-29 14:20:03 0
2 alfred 2016-06-29 14:19:58 0
and you want to sort date desc
$this->db->order_by('date', 'desc');
return $this->db->get_where('table', array('logic_erased' => 0))->result()
Active Record order by current day
If you were not paginating, you could sort the results in plain ruby like this:
day_order = %w(Tuesday Wednesday Thursday Friday Saturday Sunday Monday)
@happies = @happies.sort_by{|happy| day_order.index(happy.day)}
sort_by
takes a block that returns the value to sort by.
However, you appear to be paginating using will_paginate
. That's fine but it makes things more complicated.
The pagination necessarily happens in the database via limit and offset (so as to avoid returning the entire contents of the table to the Rails process). Therefore you want the sorting to also happen in the database. If you were to sort in ruby (as above) you would be sorting after pagination, meaning the first page would give you essentially random results, and then you'd sort them. Probably not what you want.
Long story short, you probably want to use order
instead of sort_by
, and I'm going to have to dip into SQL for this one:
@happies = Happy.where(id: @search.results.map(&:id))
.page(params[:page])
.order("CASE day WHEN 'Tuesday' THEN 0 " \
"WHEN 'Wednesday' THEN 1 " \
"WHEN 'Thursday' THEN 2 " \
"WHEN 'Friday' THEN 3 " \
"WHEN 'Saturday' THEN 4 " \
"WHEN 'Sunday' THEN 5 " \
"WHEN 'Monday' THEN 6 END")
If you want to avoid SQL, perhaps it is possible to use Arel for this, I'm not sure.
Edit
I see now you want to start with the current day, i.e. not hardcoded as Tuesday like I did. To fix my SQL version - and borrowing a bit from @Snarf's answer - you could do this:
days = %w(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
days.rotate!(days.index(Time.zone.now.strftime("%A")))
case_pieces = days.each_with_index.map do |day, i|
"WHEN '#{day}' THEN #{i}"
end
@happies = Happy.where(id: @search.results.map(&:id))
.page(params[:page])
.order("CASE day #{case_pieces.join(' ')} END")
Another thought
If I was writing the app myself, I would be tempted to store the day as an integer from 0 to 6, instead of as a string. Then you could order using the modulo operator, something like this:
days = %w(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
day_offset = days.index(Time.zone.now.strftime("%A"))
@happies = Happy.where(id: @search.results.map(&:id))
.page(params[:page])
.order("(day - #{day_offset} + 7) % 7")
Rails, how to sort the array of active records by created_at
You can sort an array by using sort_by.
In your case, you could do the following:
@total.sort_by(&:created_at)
Update:
- Remove @all << @find_user and @all_entry << @find_referal_user
- Why? Because otherwise you will have an array with multiple arrays
- Replace @total with: @total = @find_user + @find_referal_user
- Why? Because @total will now only consists of one merged array with all objects, ready to get sorted through .sort_by(&:created_at).
How do I sort data in an ActiveRecord query that are returned as a hash?
You can use sort_by
on your resulting hash, something like:
Model.where('user_id = ? AND created_at > ? AND created_at < ?', current_user.id, date1, date2).group(:something1).count.sort_by { |k, v| v }
Related Topics
How to Build a Ruby Hash Out of Two Equally-Sized Arrays
Mongodb with Mongoid in Rails - Geospatial Indexing
Where to Place/Access Config File in Gem
Jekyll on Windows: Pygments Not Working
Combinatory Method Like Tap, But Able to Return a Different Value
Setting Request Headers in Ruby
After Gem Update: Test Fail with "Asset Was Not Declared to Be Precompiled in Production"
Is It Right to Assign Multiple Variables Like This a = B = C = D = 5
Is a System-Wide Install of Rvm a Bad Idea
Manually Retry Job in Delayed_Job
Read Input from Console in Ruby
Imagemagick 7 with Rmagick 2.16 on MACos Sierra Can't Find Magickwand.H
Difference Between an It Block and a Specify Block in Rspec
Why Is Safe Navigation Better Than Using Try in Rails
How to Unit-Test a JSON Controller
Make Rake Task from Gem Available Everywhere
Fresh Installs of Rvm and Ruby 2.1.1 - Dyld Library/Pathing Error