Gugubaight Gugubaight - 2 months ago 12
Ruby Question

Rails 4 Error: NoMethodError - undefined method

I am struggling ordering my loop through my Devise Users by the upvotes on

tools
created by them.

Inside of that loop I get the value I would like to use to order the elments with:

user.tools.map(&:cached_votes_up).sum


That's my loop:

- @users.order(user.tools.map(&:cached_votes_up).sum).each do |user| #incorrect!


And my controller:

@users = User.all


Without
order
in my loop everything runs fine, with it this error appears:

NoMethodError in Users#index
Showing c:/Users/Jonas/gitapps/ocubit/app/views/users/index.html.haml where line #21 raised:

undefined method `tools' for #<Class:0xac2db78>


I am grateful for each help!

Answer

You can use joins

@users = User.joins(:tools).group("users.id").order("SUM(tools.cached_votes_up)")