![](/img/trans.png)
[英]remove search string/ query attribute from where condition for multiple attribute search. remove blank attribute for blank params from where condition
[英]How to remove blank values params from query string
我有一個包含很多選項的搜索表單,已通過“獲取請求”提交給路線。 URL是這樣的:
http://localhost:3000/restaurants/search?utf8=%E2%9C%93&city=&cuisine=&number_of_people=&query=hello
有更多的參數。 我想使其更清潔,例如刪除所有空白的參數。
像這樣:(基本上刪除所有空白的參數)
http://localhost:3000/restaurants/search?query=hello
這該怎么做?
一種方法可以使用
CGI::parse("foo=bar&bar=foo&hello=hi")
給你
{"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]}
首先在操作之間和操作之間重新引導用戶,檢查哪些參數為空並刪除它們,然后最終根據搜索的實際操作將用戶重定向。 但這聽起來很la腳。 我怎樣才能更好地做到這一點?
我的解決方案是禁用空白輸入並選擇:
$('form').submit (e) ->
$(@).find('select,input').map( (i, e) -> e.disabled = !$(e).val() )
關於刪除utf8
我發現了 。 所以我最好繼續發送它。
使用redirect_to時,在服務器上執行所有這些操作會導致一個額外的請求,因此我更喜歡使用客戶端代碼。
只是用普通的紅寶石...
require 'uri'
a = "http://localhost:8080/path/search?foo=&bar=&baz=2&bat=thing"
u = URI.parse(a)
params = u.query.split("&").select {|param| param =~ /=./}.join("&")
# Returns "baz=2&bat=thing"
在您的控制器方法中,調用remove_empty_query_params
然后作為私有方法:
def remove_empty_query_params
# Rewrites /projects?q=&status=failing to /projects?status=failing
require 'addressable/uri'
original = request.original_url
parsed = Addressable::URI.parse(original)
return unless parsed.query_values.present?
queries_with_values = parsed.query_values.reject { |_k, v| v.blank? }
if queries_with_values.blank?
parsed.omit!(:query)
else parsed.query_values = queries_with_values
end
redirect_to parsed.to_s unless parsed.to_s == original
end
我建議,如果僅查看普通的舊紅寶石,一個簡單的gsub可能就足夠了:
url.gsub(/[^\?&=]+=(?:&|$)/, '')
注意:這可能會在末尾留下一個&符號,可以用
url.chomp('&')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.