Ale*_*lex 20 ruby sorting social ruby-on-rails
我需要获取所有current_user.friends状态,然后按created_at对它们进行排序.
class User < ActiveRecord::Base
has_many :statuses
end
class Status < ActiveRecord::Base
belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)
在控制器中:
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
Run Code Online (Sandbox Code Playgroud)
current_user.friends 返回一个对象数组 User
friend.statuses 返回一个对象数组 Status
错误:
comparison of Status with Status failed
app/controllers/welcome_controller.rb:10:in `sort!'
app/controllers/welcome_controller.rb:10:in `index'
Run Code Online (Sandbox Code Playgroud)
hsg*_*ert 19
我有一个类似的问题,用to_i方法解决,但无法解释为什么会发生这种情况.
@statuses.sort! { |a,b| b.created_at.to_i <=> a.created_at.to_i }
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这按降序排序.如果你想升序是:
@statuses.sort! { |a,b| a.created_at.to_i <=> b.created_at.to_i }
Run Code Online (Sandbox Code Playgroud)
当sort从<=>返回nil时,会出现此错误消息.<=>可以返回-1,0,1或nil,但sort不能处理nil,因为它需要所有列表元素具有可比性.
class A
def <=>(other)
nil
end
end
[A.new, A.new].sort
#in `sort': comparison of A with A failed (ArgumentError)
# from in `<main>'
Run Code Online (Sandbox Code Playgroud)
调试此类错误的一种方法是检查<=>的返回值是否为nil,如果是则返回异常.
@statuses.sort! do |a,b|
sort_ordering = b.created_at <=> a.created_at
raise "a:#{a} b:#{b}" if sort_ordering.nil?
sort_ordering
end
Run Code Online (Sandbox Code Playgroud)