0

I have three models: Users, Songs, Ratings. A user has songs which other users leave ratings on. I want to create an ordered list that has the users with the highest ratings at the top.

I am able to show the average ratings received by adding this to the user model:

has_many :ratingsReceived, :through => :songs, :source => :ratings

and then in the view:

<%= user.ratingsReceived.average(:overall) %>

I just can't figure out how to make an ordered list out of this.

Any help is appreciated.

Here's how my models have the associations set up:

class Rating < ActiveRecord::Base
  belongs_to :song
  belongs_to :user

class User < ActiveRecord::Base
  has_many :songs, dependent: :destroy
  has_many :ratings
  has_many :ratingsReceived, :through => :songs, :source => :ratings

class Track < ActiveRecord::Base
  belongs_to :user
  has_many :ratings, dependent: :destroy
  • So each `song` has_may `ratings` right? and you want to show the `song` on the top that has maximum `ratings` ? – M. Karim Jun 09 '16 at 01:16
  • Would the answer on this one help you? http://stackoverflow.com/questions/19339140/ruby-on-rails-order-users-based-on-average-ratings-with-most-reviews – Taryn East Jun 09 '16 at 01:20
  • So each user had many songs and ratings, each song belongs to user and has many ratings, each rating belongs to song and user. I want to show the users with the highest average rating on their songs (it's a 1 through 5 scale), – J. Haselden Jun 09 '16 at 01:25
  • Also Taryn, I tried that one already and it didn't work. Because I'm trying to order by the ratings on the songs that belong to the user. So the songs belong to the user, and the ratings belong to the songs. The ratings don't directly associate with the users. I'm trying to get an average of all the ratings a user's songs receive, and then order the users from the highest ratings to the lowers ratings – J. Haselden Jun 09 '16 at 01:28

1 Answers1

1

According to your comment, this should do the work if user.ratingsReceived.average(:overall) working perfectly.

User.all.sort_by {|user| user.ratingsReceived.average(:overall)}.last

it will give you the user with highest ratings.

And if you want the list you can use this,

User.all.sort_by {|user| user.ratingsReceived.average(:overall)}.reverse
M. Karim
  • 932
  • 1
  • 9
  • 18
  • Hi, I'm trying to order the Users which have the highest ratings not the songs. So users have songs that receive ratings. I want to order Users by Users whose songs have received the highest ratings. – J. Haselden Jun 09 '16 at 01:35
  • Hey this worked almost perfectly! The only thing I had to do was add ' || 0' to the end because otherwise it would throw an error when a user had a song, but didn't have any ratings on it. This way they automatically get put at the end of the list. Thanks! – J. Haselden Jun 09 '16 at 13:34