[英]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.