rico_mac
rico_mac

Reputation: 888

conditionally contain arguments in url path in rails

I have a search function which allows a user to search for items. From the generated list, the user can add items to a list. After adding an item from the list, the page reloads and the user is returned to their current search list. However, currently, if a user has not searched for anything, and just adds an item of the top of the list (starting at 'A, for example), when the page reloads it includes a blank search query in the url. I know why, it is because of this line

redirect_to admin_job_job_products_path(@job, search_term: params[:search_term])

I want to make the last argument in the redirect path a conditional one so that, if say the :search_term == nil || == "" || " " then the redirect_to only includes the first argument.

How would I best achieve this?

Thanks in advance!

Upvotes: 3

Views: 1534

Answers (2)

MrYoshiji
MrYoshiji

Reputation: 54882

You can do:

if params[:search_term].present?
  redirect_to admin_job_job_products_path(@job, search_term: params[:search_term])
else
  redirect_to admin_job_job_products_path(@job)  
end

Or

redirect_to admin_job_job_products_path(@job, search_term: params[:search_term].presence)

References:

Upvotes: 3

GEkk
GEkk

Reputation: 1366

The second example of MrYoshiji probably will not work, but you can write it short and simple this why:

redirect_to admin_job_job_products_path(@job, search_term: params[:search_term].present? ? params[:search_term] : nil)

So if the result will be nil rails will not include that param in the url

Upvotes: 1

Related Questions