简体   繁体   中英

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!

您可以使用joins

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

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