在Rails中检查param存在+值的最简洁方法是什么?

时间:2023-01-19 00:17:05

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

我有一个可选的URL参数,比如我需要检查的“user_id”。我知道我可以用

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

如果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?

根据user_id参数的存在来做事情,但有时候user_id没有值传递,所以我想完全忽略它。为了解决这个问题,我发现自己做了很多 - 但必须有一个更好的方法,对吧?

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

It just seems really ugly.

它看起来真的很难看。

3 个解决方案

#1


17  

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

如果您只是检查是否存在params [:user_id],那么您可以尝试:

if params[:user_id].present?
  # do stuff
end

#2


1  

How about using Hash#fetch?

如何使用Hash #fetch?

if params.fetch(:user_id, nil).present?
  # Do stuff
end

#3


0  

Often I need to check presence of

我经常需要检查一下

params {"shoes" => {"number" => "11"}}

when I don't know if hash "shoes" exists (maybe was created dinamically !). If I try to call params[:shoes][:number] where params[:shoes] is nil I'll trigger an undefined exception.

当我不知道哈希“鞋子”是否存在时(也许是恐怖的创造!)。如果我试图调用params [:shoes] [:number],其中params [:shoes]为nil,我将触发一个未定义的异常。

Using raise I can check directly params[:shoes][:number] without trigger an exception.

使用raise我可以直接检查params [:shoes] [:number]而不会触发异常。

if(params[:shoes][:number] raise false)
  # here you can safe reading params[:shoes][:number]
  # managing exception if params[:shoes] (or [:shoes][:number]) is nil
end

I hope this helpful

我希望这有帮助

#1


17  

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

如果您只是检查是否存在params [:user_id],那么您可以尝试:

if params[:user_id].present?
  # do stuff
end

#2


1  

How about using Hash#fetch?

如何使用Hash #fetch?

if params.fetch(:user_id, nil).present?
  # Do stuff
end

#3


0  

Often I need to check presence of

我经常需要检查一下

params {"shoes" => {"number" => "11"}}

when I don't know if hash "shoes" exists (maybe was created dinamically !). If I try to call params[:shoes][:number] where params[:shoes] is nil I'll trigger an undefined exception.

当我不知道哈希“鞋子”是否存在时(也许是恐怖的创造!)。如果我试图调用params [:shoes] [:number],其中params [:shoes]为nil,我将触发一个未定义的异常。

Using raise I can check directly params[:shoes][:number] without trigger an exception.

使用raise我可以直接检查params [:shoes] [:number]而不会触发异常。

if(params[:shoes][:number] raise false)
  # here you can safe reading params[:shoes][:number]
  # managing exception if params[:shoes] (or [:shoes][:number]) is nil
end

I hope this helpful

我希望这有帮助