简体   繁体   中英

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.

@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.

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:

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

You could try to loop through the results in MatchResult and push each one into first array:

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.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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