按分数对用户排序。正在呈现的数字而不是名称

时间:2014-01-04 02:48:51

标签: ruby-on-rails ruby

enter image description here

我的用户名称的数据库列为first_name。分数不是指南数据库中的一列。

在我的业力控制者中:

  def hiscores
    @users = User.all.map(&:guides).flatten.map(&:score).sort
  end

在hiscores.html.erb

<h1>Karma Hiscores</h1>
<blockquote>Users sorted by most karma</blockquote>


<ul>
  <% @users.each do |user| %>
  <li><%= user %></li>
  <% end %>
</ul>

EDITS

指南模型

class Guide < ActiveRecord::Base
  validates :link, uniqueness: true
  validates :link, presence: true
  validates :title, presence: true 

  belongs_to :user
  has_many :comments


  acts_as_taggable
  acts_as_votable

  def to_param
    "#{id} #{title}".parameterize
  end

  def score
    upvotes.count - downvotes.count
  end


end


User.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, #:recoverable,
          :rememberable, :trackable, :validatable

  validates :first_name, presence: true
  validates :email, presence: true
  validates :email, uniqueness: true
  validates :runescape_username, presence: true

  has_many :guides
  has_many :comments

  acts_as_voter





end

这是我的业力控制器现在的样子:

class KarmaController < ApplicationController
  def hiscores
    @users =  (guides.upvote.count - guides.downvote.count).desc
  end
end

2 个答案:

答案 0 :(得分:1)

在你的业力控制器中:

def hiscores
  @users = User.all.sort{ |x, y| y.user_score <=> x.user_score }
end

在您的User.rb中:

如果每个用户都有_many:指南,那么

def user_score
  self.guides.inject(0) { |sum, guide| sum += guide.score }
end

否则,如果每个用户has_one:guide,那么

def user_score
  self.guide.score
end

答案 1 :(得分:0)

这样的事情怎么样:

@users = User.find(:all, include: [:guides], order: "(guides.upvotes.count - guides.downvotes.count) desc")

我不确定是否需要包含,我正在从头顶打字:)

修改

您应该尝试使用acts_as_votable中的Caching

这会为您提供cached_votes_upcached_votes_down以及cached_votes_score等字段。

然后您可以将用户视为

@users = User.find(:all, include: [:guides], order: "guides.cached_votes_score desc")