Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 528
jbnunn Avatar asked Oct 03 '12 14:10

jbnunn


1 Answers

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

if params[:user_id].present?
  # do stuff
end
like image 191
gerky Avatar answered Nov 15 '22 19:11

gerky