HUSTEN
HUSTEN

Reputation: 5197

How can I get ranking of records by the column of associated table

User has one UserProfile, and UserProfile belongs to User

There is a column called total_point in UserProfile table.
and I'd like to sort by this column.

so I tried this but I get this error. Why? How can I modify?

Error

wrong number of arguments (1 for 0)

Controller

@rank = User.confirmed.joins(:user_profile).order('user_profiles.total_point ASC').index(current_user)

View

Rank: <%= @rank %>

Upvotes: 0

Views: 588

Answers (1)

JellyFishBoy
JellyFishBoy

Reputation: 1798

If this order behaviour is going to be used across a number of views, you'd be better off placing this logic in the model to keep your views clean:

class User < ActiveRecord::Base

   default_scope joins(:user_profile).order('user_profiles.total_point ASC')

end

This default logic can also be overridden, when required, by just calling the order method mentioned above on your collection/array. It's good to get into the habit of keeping the majority of the business logic in your models/library.

Upvotes: 1

Related Questions