Rails 3 - IF语句在NIL上没有中断

AnA*_*ice 2 ruby-on-rails ruby-on-rails-3

我有以下if语句:

if !projectid_viewing.nil? && !user.role(projectid_viewing).nil? && user.role(projectid_viewing) == 'admin'
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用上面的内容,不是if break是projectid_viewing或user.role是nil.projectid_viewing似乎工作得很好但user.role不断破坏,给出以下错误:

undefined method `role' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

你能用if语句帮助我,是否有更优雅的方式来编写语句?

Chr*_*ris 5

您需要确保用户也不是零.

Note that in Ruby, a value of nil in a conditional statement will be interpreted as false. Thus, if you use a variable with a nil value in a conditional statement, it will also evaluate to false. Knowing this, you can simplify statements like !projectid_viewing.nil? to just the name of the variable, and it will work just the same.

if projectid_viewing && user && user.role(projectid_viewing) == 'admin'
Run Code Online (Sandbox Code Playgroud)

The above is just plain Ruby, but you said you're using Rails 3. Rails has a neat little method: Object#try. It would allow you to simplify this statement further to the following:

if projectid_viewing && user.try(:role, projectid_viewing) == 'admin'
Run Code Online (Sandbox Code Playgroud)

The Object#try method will protect you if the value of user is nil, and that entire second part of the expression will return nil (i.e., false).

  • 答案还可以,但是`nil == false`不会返回'true`! (2认同)