【问题标题】:How to persist scopes across requests with Rails and HasScope?如何使用 Rails 和 HasScope 跨请求保持范围?
【发布时间】:2014-11-16 08:18:27
【问题描述】:

我有一个简单的搜索和过滤页面。

类产品(型号):

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

作用域按预期工作(例如)

products?search=computer

products?search=computer&country=australia

products?country=australia

问题场景: 当我想在搜索后按国家/地区过滤结果时,我无法建立正确的查询字符串。

搜索视图:

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

生产:

/products?search=xxx

没关系。

过滤视图:

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

生产:

/products?country=xxx

这会覆盖整个 URL。过滤时如何获取这样的URL。

/products?search=xxx&country=xxx

当我想过滤结果时如何保留搜索查询字符串?

【问题讨论】:

    标签: ruby-on-rails ruby query-string actionview named-scope


    【解决方案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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      相关资源
      最近更新 更多