I have an array of appointment objects, and I would like to sort by starts_at attribute.
my_array.uniq.sort_by! {|obj| obj.starts_at}
However, I got the following error:
comparison of ActiveSupport::TimeWithZone with nil failed
I am sure I don't have any nil value for starts_at. What's the problem here? Also, how can I sort by descending?
Update 1: I realized that uniq! gives me nil when I call .all method to my Appointment class. Without uniq, it works fine.
Appointment.all.uniq!
Update 2: I can't apply minus to obj.starts_at. It gives me error:method - can't be found with UTC time format. Probably b/c time does not allowed to be zero. Any thoughts on overcome this?
Update 3: my_array.uniq.sort { |x, y| (x.starts_at || nil) <=> (y.starts_at || nil)}
works in console, but when I ran my app, it says comparison of Event with Event failed
Last update: The following works:
@events.sort_by!{|obj| (obj.starts_at.nil? ? 3.years.ago : obj.starts_at.utc)}
I need to convert date format to .utc, and handle missing starts_at (sorry I don't know why I have missing starts_at attribute on an object)
I have association of blog_post has many blog_comments and i sort array of blog_post according
to blog_comments count and it is running fine......
@sort_blog = @blog_posts.sort_by { |i| i.blog_comments.count }
I think you are doing fine but problem is some where you have nil object you can try like this
my_array.uniq.sort_by! {|obj| obj.starts_at unless obj.blank?}
Try it.........
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With