sort_by或来自关联模型的行

时间:2013-02-08 00:27:33

标签: ruby-on-rails-3

我正在尝试对提交的索引进行排序。

每次提交has_one :score和得分belongs_to :submission提交belongs_to :contest和竞赛has_many :submissions

我想要排序的行在提交> index

中是submission.score.subtotal

我试过这个:

 @submissions = submission.find(:all, :include => :score).sort_by { |s| s.scores.sub_total }.paginate(:per_page => 10, :page => params[:page])

我已经在第一场比赛中为所有提交内容分配了分数,但是当我尝试提交提案>第一场比赛的索引(通过参数指定)时,我收到了错误:

NoMethodError at /submissions
undefined method `sub_total' for nil:NilClass

我很确定我需要在某个地方检查nil,但我错过了那里。

更多信息:

def index
  contest_id = params[:contest_id]
  @contest = Contest.find(contest_id)
  submission = Submission.where(:contest_id => params[:contest_id])
  if params[:search].blank?
   @submissions = submission.find(:all, :include => :score).sort_by { |s| s.score.sub_total }.paginate(:per_page => 10, :page => params[:page])
  else 
   @submissions = submission.search(params[:search]).paginate(:per_page => 10, :page => params[:page])
  end
   @search = params[:search] 
end

1 个答案:

答案 0 :(得分:1)

此代码应该满足您的需求:

@submissions = Submission.find(:all, :joins => :score, :order => 'scores.sub_total DESC').paginate(:per_page => 10, :page => params[:page])

我希望这有助于你