繁体   English   中英

用于#的未定义方法`updated_at&#39; <MatchResult::ActiveRecord_Relation:0x0000000232e608> 在铁轨

[英]undefined method `updated_at' for #<MatchResult::ActiveRecord_Relation:0x0000000232e608> in rails

我有两个活动记录数组。 我合并了这两个数组,现在我想根据“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”函数。

在你的情况下MatchResult可能返回一个MatchResult对象,其中包含一个记录数组,所以当你将MatchResult添加到你的第一个数组时,你最终会得到类似的东西:

[a, b, c, MatchResult[d, e, f]]

其中此数组中的第4个元素是没有update_at属性或方法的MatchResult对象。

您可以尝试在MatchResult循环遍历结果并将每个结果推送到第一个数组中:

results = MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)
@match_results = results.map{|c| @match_results << c}

只是一个想法,因为我不确定MatchResult在你的情况下返回什么。

MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)

已经返回一个数组(坦率地说是一个ActiveRecord :: Relation)。 所以,不应该推。 你应该补充一下。

我觉得将@notification_challenges初始化为空数组也更好。 以防万一...

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM