2014-09-22 50 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