Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty parameters from params hash?

In my Rails 4 application I have this setup:

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 a bunch of other GET parameters which are all part of the params hash. How can I remove the blank parameters from the URL so that I don't end up with URLs like:

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

Thanks for any help.

like image 281
Tintin81 Avatar asked Jul 24 '14 17:07

Tintin81


People also ask

How do you remove Blank strings from an array in Ruby?

Use compact_blank to remove empty strings from Arrays and Hashes.

Is params a hash?

While params appears to be a hash, it is actually an instance of the ActionController::Parameters class.

What does params permit do?

Strong Params allow developers to specify in the controller which parameters are accepted and used. By permitting only the expected params, any unneeded or potentially dangerous params will be ignored and effectively filtered out.

What is params hash in rails?

Specifically, params refers to the parameters being passed to the controller via a GET or POST request. In a GET request, params get passed to the controller from the URL in the user's browser.


2 Answers

Put this after the hash:

.reject{|_, v| v.blank?}
like image 54
sawa Avatar answered Sep 16 '22 16:09

sawa


Rails 6.1+

Rails 6.1 added compact and compact! to ActionController::Parameters in order to remove nil values from params hash.

params.compact

params.compact!

Here is a link to PR.


Rails 6.1 added compact_blank and compact_blank! to ActionController::Parameters in order to remove blank values from params hash.

params.compact_blank

params.compact_blank!

Here is a link to PR.

Examples of blank values:

nil, '', ' ', [], {}, false
like image 45
Marian13 Avatar answered Sep 18 '22 16:09

Marian13