2014-12-05 37 views
0

我有一個模型商店,具有屬性的數據庫:商店名稱,開店一年,總銷售額(以及更多)。我已經做了這個數據和它的結果的一些統計數據是這樣的表格:Rails - 用戶選擇的過濾器

enter image description here

現在,我要的是讓用戶選擇/輸入年份,並且該應用程序只顯示以下數據那年(而不是整個表)

我的表部分shop.rb:

class Shop < ActiveRecord::Base 
    belongs_to :opened 
    def self.percentile(values, percentile) 
    values_sorted = values.sort 
    k = (percentile*(values_sorted.length-1)+1).floor - 1 
    f = (percentile*(values_sorted.length-1)+1).modulo(1) 
    return values_sorted[k] + (f * (values_sorted[k+1] - values_sorted[k])) 
    end 

    def self.median_by_year 
    arr ||= [] 
    years = Shop.distinct.pluck(:year).sort 
    years.each do |yr| 
     sales = Shop.where(year: yr).pluck(:items_sold) 
     perc = percentile(sales, 0.5) 
     arr << perc.to_i 
    end 
    return arr 
    end 
end 

我的控制器:

class ShopsController < ApplicationController 
    def index 
    @count = Shop.count 
    @sales_average = Shop.average(:items_sold).to_i 

    @sold = Shop.pluck(:items_sold) 
    @top_twenty_sales_average = Shop.percentile(@sold, 0.80).to_i 
    @bottom_twenty_sales_average = Shop.percentile(@sold, 0.20).to_i 
    @median = Shop.percentile(@sold, 0.50).to_i 

    @average_sales_by_year = Shop.select('year, count(names) as count').group('year').order('year').average('items_sold') 
    @min_sales_by_year = Shop.select('year, count(names) as count').group('year').order('year').minimum('items_sold') 

    @med = Shop.median_by_year 
    @table = @[email protected]@min_sales_by_year 
    end 

終於表視圖文件

<table> 
    <thead> 
     <tr> 
      <th>Year</th> 
      <th>Average sales</th> 
      <th>Median sales</th> 
      <th>Min sales</th> 
     </tr> 
    </thead> 
    <tbody> 
     <% @table.each do |avg, med| %> 
     <tr> 
      <td><%= avg[0] %></td> 
      <td><%= avg[1].to_i.to_s %></td> 
      <td><%= med[0] %></td> 
      <td><%= med[1][1] %></td> 
     </tr> 
     <% end %> 
    </tbody> 
</table> 

爲了創建過濾器我想基於相似的,所以問題一大堆東西,但是這是我的第一個應用程序不斷,所以基本上我不明白不夠知道做什麼。到目前爲止,我試圖將其添加到模型:

def self.by_year(selected_year=nil) 
    if year 
     where(year: selected_year) 
    else 
     scoped 
    end 
    end 

此控制器:

@shops = Shop.select(params[:year]) 

最後這個視圖:

<%= form_tag url: shops_path do %> 
     <%= select_tag :year %> 
     <%= submit_tag 'Filter' %> 
<% end %> 

,但我真的不知道這是否正確,或者如何繼續。任何幫助將不勝感激。

+1

在你的控制器索引中,你必須添加一個if。 @shop = Shop.select(params [:year])if params [:year]。並在你的form_for方法:: get – argentum47 2014-12-05 06:11:45

+0

嗨,謝謝你的評論。但這仍然沒有給我實際的過濾器,只是一個空的形式。 – user1754606 2014-12-05 16:19:33

+1

你的意思是你得到一個空的表單,然後你輸入一些內容並點擊過濾器,你仍然會得到一個空的表單?你有沒有檢查你的控制檯日誌,看是否有任何查詢運行,你是否嘗試<%= raise @ shop.inspect%>,看看你的瀏覽器中是否有商店列表作爲錯誤消息? – argentum47 2014-12-06 07:30:09

回答

1

它很可能是清潔劑來爲你的表比與當年範圍這一觀點的一個單獨的模型

class ShopStats < ActiveRecord::Base 
    scope :for_year, ->(year) { where(:year => year)} 
end 

比你的控制器,你可以有一個觀點:

ShopStats.for_year params[:year]