I need to fetch all current_user.friends statuses and then sort them by created_at.
class User < ActiveRecord::Base
has_many :statuses
end
class Status < ActiveRecord::Base
belongs_to :user
end
And in the controller:
def index
@statuses = []
current_user.friends.map{ |friend| friend.statuses.each { |status| @statuses << status } }
current_user.statuses.each { |status| @statuses << status }
@statuses.sort! { |a,b| b.created_at <=> a.created_at }
end
current_user.friends returns an array of objects User
friend.statuses returns an array of objects Status
Error:
comparison of Status with Status failed
app/controllers/welcome_controller.rb:10:in `sort!'
app/controllers/welcome_controller.rb:10:in `index'
I had a similar problem, solved with the to_i method, but can’t explain why that happens.
By the way, this sorts in the descending order. If you want ascending order is: