[英]undefined method `updated_at' for #<MatchResult::ActiveRecord_Relation:0x0000000232e608> in rails
I have two active record array. 我有两个活动记录数组。 I merged these two arrays and now I want to sort them according to "updated_at" field.
我合并了这两个数组,现在我想根据“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
but it is giving following error : 但是它给出了以下错误:
undefined method `updated_at' for #<MatchResult::ActiveRecord_Relation:0x0000000232e608>
and 和
@notifications=(@match_results+@notification_challenges).sort_by(&:updated_at)
is working fine. 工作正常。 But I want to check that @match_results or @notification_challenges is blank or not so I am merging these two arrays and then applying "sort_by" functions.
但我想检查@match_results或@notification_challenges是否为空,所以我合并这两个数组,然后应用“sort_by”函数。
MatchResult
in your case probably returns an MatchResult
object with an array of records in it, so when you add MatchResult
to your first array you'll end up having something like: 在你的情况下
MatchResult
可能返回一个MatchResult
对象,其中包含一个记录数组,所以当你将MatchResult
添加到你的第一个数组时,你最终会得到类似的东西:
[a, b, c, MatchResult[d, e, f]]
where the 4th element in this array is the MatchResult
object that does not have update_at
attribute or method. 其中此数组中的第4个元素是没有
update_at
属性或方法的MatchResult
对象。
You could try to loop through the results in MatchResult
and push each one into first array: 您可以尝试在
MatchResult
循环遍历结果并将每个结果推送到第一个数组中:
results = MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)
@match_results = results.map{|c| @match_results << c}
Just an idea, cause I am not sure what MatchResult
returns in your case. 只是一个想法,因为我不确定
MatchResult
在你的情况下返回什么。
MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)
already returns an array(Frankly speaking an ActiveRecord::Relation). 已经返回一个数组(坦率地说是一个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. 我觉得将@notification_challenges初始化为空数组也更好。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.