How to remove empty parameters from params hash?

In my Rails 4 application, I have this setting:

class InvoicesController < ApplicationController def index @invoices = current_user.invoices.search(params) end ... end 

 class Invoice < ActiveRecord::Base belongs_to :user def self.search(params) data = all data = data.where("number LIKE ?", "%#{params[:number]}%") if params[:number] data = data.where("total > ?", params[:minimum]) if params[:minimum] data = data.where("total < ?", params[:maximum]) if params[:maximum] data end ... end 

The problem is that I have many other GET parameters that are part of the params hash. How can I remove empty parameters from a URL so that I don't have URLs like:

 /invoices?after=&before=&maximum=&minimum=&number= 

Thanks for any help.

+8
ruby ruby-on-rails activerecord
source share
2 answers

Put this after the hash:

 .reject{|_, v| v.blank?} 
+22
source share

For search forms, I wanted to remove the parameters from the client side URL, especially if there are many fields in the advanced search. Tries for a clean URL for bookmarks and sharing.

Here is a coffee script for this ...

 $(document).on 'ready page:load', -> $('#search_form').submit -> $(this).find(':input').filter(-> !@value ).prop 'disabled', true true # If they hit back $('#search_form').find(':input').prop 'disabled', false # If they stop page load and click on the form again it enables $('#search_form').on 'click', -> $(this).find(':input').prop 'disabled', false return 
+1
source share

All Articles