从关联表中订购模型

时间:2015-06-11 08:58:31

标签: ruby-on-rails

我有一个我称之为“Idee”的模型,我想按日期和受欢迎程度订购此模型(有一个投票系统)。我跟着this railcast。它有效,但只有日期,投票存储在投票表中,这是我的关联:

投票

belongs_to :idee
belongs_to :user

用户 has_many :votes, dependent: :destroy

Idee has_many :votes, dependent: :destroy

而且我不知道我怎么能说Idee是通过投票的顺序,因为投票数是在投票表上而不是在Idee中所以如果我说按投票排序他想找到一个列投票在我的想法。所以这就是我现在所做的:

应用程序助手

def sortable(column, title = nil)
   title ||= column.titleize
   direction = (column == params[:sort] && params[:direction] == "asc") ? "desc" : "asc"
   link_to title, :sort => column, :direction => direction
end

控制器

  def publiee
  @idees = Idee.order(sort_column + " " + sort_direction)
  @activites = Activite.all
  end

    private
  def sort_column
    params[:sort] || "created_at"
  end

  def sort_direction
    params[:direction] || "asc"
  end

查看

<%= sortable "created_at", "Date" %>

有没有办法按照我现在所做的做到我想做的事情?

PS:我的“Idee”未显示在<table>

2 个答案:

答案 0 :(得分:2)

请使用joins

def publiee
  @idees = Idee.order_idess_by_votes sort_column, sort_direction
  @activites = Activite.all
end

Idee模型中,下面的代码应该

scope :order_idess_by_votes, ->(sort_column, direction) { joins(:votes).order("#{order_expr(sort_column, direction)}, COUNT(votes.id) DESC)") }

private 

def order_expr sort_column, direction
  # list all possible columns that you want to use in ORDER clause
  # to SQL
  order_mappings = {
    'first_name_asc'  => 'first_name ASC',
    'first_name_desc' => 'first_name DESC',
    'created_at_asc'  => 'created_at ASC',
    'created_at_desc' => 'created_at DESC',
    # .....
  }

  order_mappings["#{sort_column}_{direction}"]
end

答案 1 :(得分:0)

<{1>}模型类中的

Idee

然后在控制器中:

scope :with_votes_count, -> { select("idees.*, count(votes.id) as votes_count").references(:votes).includes(:votes).group('idees.id') }

现在,您所要做的就是将def publiee @idees = Idee.with_votes_count.order("#{sort_column} #{sort_direction}") @activites = Activite.all end private def sort_column column = params[:sort] || 'created_at' Idee.columns.include?(column) ? column : "created_at" end 传递给&#34; sort_column&#34;和votes_count as&#34; sort_direction&#34;或&#34; DESC&#34;因为你希望它能够发挥作用。

相关问题