gpt4 book ai didi

ruby-on-rails - rails : comparison of Status with Status failed

转载 作者:数据小太阳 更新时间:2023-10-29 06:32:04 28 4
gpt4 key购买 nike

我需要获取所有 current_user.friends 状态,然后按 created_at 对它们进行排序。

class User < ActiveRecord::Base
has_many :statuses
end

class Status < ActiveRecord::Base
belongs_to :user
end

在 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 返回对象数组 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'

最佳答案

我有一个类似的问题,用 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 }

关于ruby-on-rails - rails : comparison of Status with Status failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077180/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com