ruby-on-rails – Rails:状态与状态的比较失败

我需要获取所有current_user.friends状态,然后通过created_at进行排序.
class User < ActiveRecord::Base
 has_many :statuses
end

class Status < ActiveRecord::Base
 belongs_to :user
end

在控制器中:

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返回一个对象数组

friend.statuses返回一个对象的数组状态

错误

comparison of Status with Status Failed
app/controllers/welcome_controller.rb:10:in `sort!'
app/controllers/welcome_controller.rb:10:in `index'

解决方法

我有一个类似的问题,用to_i方法解决,但不能解释为什么会这样.
@statuses.sort! { |a,b| b.created_at.to_i <=> a.created_at.to_i }

顺便说一句,这是按降序排序的.如果你想升序是:

@statuses.sort! { |a,b| a.created_at.to_i <=> b.created_at.to_i }

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...