【问题标题】:Sorting my Rails Table对我的 Rails 表进行排序
【发布时间】:2013-04-09 21:44:54
【问题描述】:

我的控制器:

def index
  @unique_bug = Rating.find_by_sql("SELECT bug FROM ratings WHERE bug <> '' GROUP BY bug")
end

评级模型:

  def self.metrics_bug_count(bug)
    count = where(bug:"#{bug}").count
    total = Rating.find_by_sql("SELECT bug FROM ratings WHERE bug <> ''").count
    percentage = (count.to_f/total.to_f * 100)
    return count, percentage
  end

我的看法:

 <table class="table table-bordered">
  <tr>
  <th><h3>Bug</h3></th>
  <th><h3>Total Occurrences</h3></th>
  <th><h3>Frequency</h3></th>  
  </tr>
  <tr>
  <%@unique_bug.each do |rating| %>
  <% count, percentage = Rating.metrics_bug_count(rating.bug)%>
  <td><p class="text-center"><h4><%= rating.bug.capitalize %></h4></p></td>
  <td><p class="text-center"><h4><%= count %></h4></p></td>
  <td><p class="text-center"><h4><%= number_to_percentage(percentage, :precision => 2)%></h4></p></td>
  </tr>
  <%end%>
  </table>

如何使每一行(Bug、Total、Frequency)都可以排序?我在可排序表上观看了Railscast 剧集,但是那里的排序是在控制器中完成的。如何使用在我的模型中执行的更复杂的查找对我的表进行排序。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    您可以使用 .order 例如,Rating.order("count DESC")。 此外,我认为您可以避免使用 find_by_mysql 并使用一些 rails 方法来进行更易读和更容易的查询。 您也可以使用 .uniq 获得唯一的 1。

    试试看 http://guides.rubyonrails.org/active_record_querying.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2011-05-18
      相关资源
      最近更新 更多