BB500
BB500

Reputation: 559

Rails scope that orders Users by a Reputation Score

I have a users table and I keep a reputation score on each user. The reputation score is the combined score from 2 factors:

  1. total followers on the Users projects (projects he/she created)

  2. total votes on the Users tasks (tasks that he/she created)

My goal is to allow users to filter users by most recent (the standard index action) or by users with the most reputation. What Rails scope would give back the list of Users ordered by this 'total reputation score' in order of highest score to lowest? thx,

My code is as follows:

User.RB Model

def total_reputation_score
  project_follower_count + task_vote_count
end

scope :by_reputation, -> { #HOW DO I CREATE THIS SCOPE? }

Users Controller

def index
  @users = User.text_search(params[:query]).paginate(page: params[:page], :per_page => 12)
end

  def most_reputation
    @users = policy_scope(User)
    @users = @users.
      text_search(params[:query]).
      by_reputation.
      paginate(page: params[:page], :per_page => 12)

    render :index
  end

Upvotes: 1

Views: 76

Answers (1)

coreyward
coreyward

Reputation: 80041

While you can do this in SQL on the fly, you really want to:

Add a counter cache for each of the two count items shown here; this adds these as calculated columns that Rails will maintain for you, then do this for your scope:

User.order(User.arel_table[:project_follower_count] + User.arel_table[:task_vote_count]).reverse_order

(or something similar)

Alternately you can double down on your RDBMS and build out indices to handle on the fly.

Upvotes: 3

Related Questions