Alex Rivera | Logout

What's your most succinct way of checking param existence + value in Rails?

Asked 2012-10-03T14:35:19.537
9

I have an optional URL param, say "user_id" I need to check for. I know I can use

if params.has_key?(:user_id) ...

to do things based on the presence of the user_id parameter, but sometimes user_id is passed without a value, so I want to ignore it completely. To fight the issue, I find myself doing this a lot--but there's got to be a better way, right?

if params[:user_id] && !params[:user_id].empty?
  # Do stuff
end

It just seems really ugly.

Edit
Report

1 Answer

17

If you're just checking if params[:user_id] is present, then you can try:

if params[:user_id].present?
  # do stuff
end
answered 2012-10-03T14:44:51.580

Your Answer