Rails 3:在排行榜中按类别过滤优点

时间:2014-05-22 19:03:14

标签: ruby-on-rails ruby-on-rails-3 merit-gem

我面临的真正的战术问题是所有类别都设置为'默认'因此,如果我选择[:category] ​​='默认'它只添加没有类别的点。因此,如果我为cateogry添加积分' arin'它不会计入默认值'总。所以我尝试抓住所有表格,如果不是NULL或按类别,但它会继续为#ar;'#抓住相同的数量。

默认值:20

arin:20

如果没有提供类别或默认情况下应该总共40个,如果params category' arin'那应该是20。

有人可以帮助我理解正确的SQL背后的概念,以获得我想要的结果吗?

rails和SQL新手。

  def self.top_scored(options = {})
   options[:table_name] ||= :users
   options[:since_date] ||= 4.months.ago
   options[:end_date] ||=  1.month.from_now
   options[:category] ||=  nil
   options[:limit]      ||= 10

  alias_id_column = "#{options[:table_name].to_s.singularize}_id"
  if options[:table_name] == :sashes
    sash_id_column = "#{options[:table_name]}.id"
  else
    sash_id_column = "#{options[:table_name]}.sash_id"
  end

  # MeritableModel - Sash -< Scores -< ScorePoints
  sql_query = <<SQL
SELECT
  #{options[:table_name]}.id AS #{alias_id_column},
  SUM(num_points) as sum_points
FROM #{options[:table_name]}
  LEFT JOIN merit_scores ON merit_scores.sash_id = #{sash_id_column}
  LEFT JOIN merit_score_points ON merit_score_points.score_id = merit_scores.id
WHERE merit_score_points.created_at > '#{options[:since_date]}' AND merit_score_points.created_at < '#{options[:end_date]}' AND (merit_scores.category IS NOT NULL OR merit_scores.category = '#{options[:category]}')
GROUP BY #{options[:table_name]}.id, merit_scores.sash_id
ORDER BY sum_points DESC
LIMIT #{options[:limit]}
SQL

  results = ActiveRecord::Base.connection.execute(sql_query)
  results.map do |h|
    h.keep_if { |k, v| (k == alias_id_column) || (k == 'sum_points') }
  end
  results
end
  end

1 个答案:

答案 0 :(得分:0)

似乎没有人回答,只有投票。以下是任何对此有疑问的人。我想你可以拆分sql语句并在SQL中的rails中使用if语句。

  sql_query = "SELECT
                #{options[:table_name]}.id AS #{alias_id_column},
                SUM(num_points) as sum_points
              FROM #{options[:table_name]}
                LEFT JOIN merit_scores ON merit_scores.sash_id = #{sash_id_column}
                LEFT JOIN merit_score_points ON merit_score_points.score_id = merit_scores.id
              WHERE merit_score_points.created_at > '#{options[:since_date]}' AND merit_score_points.created_at < '#{options[:end_date]}' "

  if(options[:category] != nil)
    sql_query += "AND merit_scores.category = \"#{options[:category]}\" "
  end

  sql_query += "GROUP BY #{options[:table_name]}.id, merit_scores.sash_id
                ORDER BY sum_points DESC
                LIMIT #{options[:limit]} "

  results = ActiveRecord::Base.connection.execute(sql_query)