我有两个活动记录数组。我合并了这两个数组,现在我想根据“updated_at”字段对它们进行排序。
@notification_challenges=Challenge.where("to_id=? and activity_id=?" ,current_user.id,@activity.id)
@match_results=[]
@notification_challenges.each do |k|
@match_results=@match_results<<MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)
end
if !@match_results.blank?
@notifications=@notifications+@match_results
end
if !@notification_challenges.blank?
@notifications=@notifications+@notification_challenges
end
if !@notifications.blank?
@notifications2=(@notifications).sort_by(&:updated_at)
@notifications2=@notifications.reverse
end
但它出现以下错误:
undefined method `updated_at' for #<MatchResult::ActiveRecord_Relation:0x0000000232e608>
和
@notifications=(@match_results+@notification_challenges).sort_by(&:updated_at)
工作正常。 但我想检查@match_results或@notification_challenges是否为空,所以我合并这两个数组,然后应用“sort_by”函数。
答案 0 :(得分:2)
MatchResult
可能会返回一个包含记录数组的MatchResult
对象,因此当您向第一个数组添加MatchResult
时,您最终会得到一些东西像:
[a, b, c, MatchResult[d, e, f]]
此数组中的第4个元素是没有MatchResult
属性或方法的update_at
对象。
您可以尝试在MatchResult
中遍历结果并将每个结果推送到第一个数组中:
results = MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)
@match_results = results.map{|c| @match_results << c}
只是一个想法,因为我不确定你的案例中MatchResult
会返回什么。
答案 1 :(得分:1)
MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)
already returns an array(Frankly speaking an ActiveRecord::Relation). So, should not push. You should be adding.
And I feel it is better to initialize @notification_challenges to an empty array too. Just in case...
@notification_challenges=[]
@notification_challenges=Challenge.where("to_id=? and activity_id=?" ,current_user.id,@activity.id)
@match_results=[]
@notification_challenges.each do |k|
@match_results=@match_results + MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)
end