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.
Use compact_blank to remove empty strings from Arrays and Hashes.
While params appears to be a hash, it is actually an instance of the ActionController::Parameters class.
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.
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.
Put this after the hash:
.reject{|_, v| v.blank?}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With