2014-09-22 52 views
1

我有一個簡單的搜索和過濾頁面。如何使用Rails和HasScope持久化範圍?

類產品(模型):

scope :country, ->(country){ where(:country => country) } 
scope :search, ->(search) { where(arel_table[:name].matches("%#{search}%")) } 

類ProductController的(控制器):

has_scope :country 
has_scope :search 

def index 
    @products = apply_scopes(Product) 
end 

範圍是如預期(例如)

產品的工作?搜索=電腦

產品搜索=計算機&國家=澳大利亞

產品國家=澳大利亞

問題場景:?? 當我想要搜索後過濾按國家的結果我無法建立正確的查詢字符串。

搜索查看:

=form_tag products_path, :method => 'get' do 
    =text_field_tag :search, '', placeholder: "Enter name of product" 
    %button{:type => "submit"} 

主要生產:

/產品搜索= XXX

它是沒問題。

過濾視圖:

=form_for :country, :method => :get do |f| 
    =f.collection_select :country, @countries, :id, :country 
    =f.submit "Search" 

主要生產:

/產品的國家= XXX

這會覆蓋整個URL。過濾時如何獲得這樣的URL。

/products? 搜索= XXX &國家= XXX

我怎能搜索字符串時,我想過濾的結果嗎?

回答

1

您可以將隱藏字段添加到您的過濾器的形式,與過濾器一起,將重新提交當前搜索:

= form_for :country, :method => :get do |f| 
    = f.hidden_field :search, value: params[:search] 
    = f.collection_select :country, @countries, :id, :country 
    = f.submit "Search" 
+0

謝謝您的回答!有用! – user3572412 2014-09-22 11:37:18