简体   繁体   English

Ruby on Rails-处理未设置或不存在的变量

[英]ruby on rails - dealing with variables not being set or not existing

I was wondering if there is a better way to check if a variable exists, currently I do this 我想知道是否有更好的方法来检查变量是否存在,目前我正在这样做

if !params['attribute']['institution'].blank?

But if attribute doesn't exist then a error is thrown. 但是,如果属性不存在,则会引发错误。

I saw .try() but couldn't see how it would work in this situation. 我看到了.try()但看不到在这种情况下它将如何工作。

Also can anyone recommend a good ruby book or ruby web resource ? 也有人可以推荐一本好的红宝石书或红宝石网络资源吗?

Thanks 谢谢

Alex 亚历克斯

You can use present? 您可以使用present? or presence which was recently described by a blog post by Ola Bini. presence最近被所描述的博客文章由奥拉·比尼。

if params['attribute'] && params['attribute']['institution']

不是最漂亮的,但是有效。

You can use if params['attribute'].has_key? 'institution' 您可以使用if params['attribute'].has_key? 'institution' if params['attribute'].has_key? 'institution'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM