I have the search form and the results of the search posted on the same page.
As I understand it: the default for ransack is that if a form is submitted with no values inputted into the search fields, then all records of that particular resource are returned.
How can I change it so that if a user does a search where they enter no values into the search fields, then none of the records are returned?
This doesn't work:
if params["q"].values.present? # Always returns true because an array of empty strings returns true from method call: present?
# do this
else
# do that
end
Neither does this:
if params["q"].values.empty? # Always returns true because an array of empty strings returns true from method call: empty?
# do this
else
# do that
end
Checking for params["q"].present?
does not work either because every time a form is submitted, whether there are values entered or not, this is what gets passed through to the server:
# showing with pry
[1] pry> params[:q]
=> {"namesearch_start"=>"",
"city_cont"=>"",
}
[2] pry> params[:q].present?
=> true # always returns true
So params["q"]
will always be present, whether there are values entered or not.
What you can do is reject any values that are blank.
if params[:q].reject { |_, v| v.blank? }.any? # .none? for inverted
# Handle search
else
# Handle no query scenario
end
Or
if params[:q].values.reject(&:blank?).any? # .none? for inverted
# Handle search
else
# Handle no query scenario
end