Ruby检查记录是否存在以及一行是否存在关联

时间:2019-10-25 10:15:52

标签: ruby-on-rails ruby if-statement

我总是会碰到的东西。我要这样做:

if current_user.exists? && current_user.role == "admin"
  # Do something
end

很明显,如果当前用户不存在,那么它将返回undefined method role for nil class

有没有一种方法可以在没有多条If语句的情况下实现上述目的?

2 个答案:

答案 0 :(得分:5)

尝试:

<div class="player">
  <div class="artist-title-infos">
    <span class="cover"><img class="picture" src="http://my-cover" alt="cover"></span>
    <div class="infos">
      <button class="buttonPlayer notPlaying"><i id="iconPlayer" class="fas fa-play-circle"></i></button>
      <button class="pausePlayer notPaused"><i id="iconPlayer" class="fas fa-pause-circle"></i></button>
      <span class="artist">Now : </span>
      <span class="title">Your song</span>
     </div>
    </div>
   <div class="next-container">
    <span class="next">Next : </span>
    <span class="next next-songs-0">Your song 1</span>
    <span class="next next-songs-1">, Your song 2</span>
    <span class="next next-songs-2"> & Your song 3</span>
   </div>
</div>

if current_user&.role == "admin" 是一个安全的导航器-如果之前的部分为nil,则方法链的其余部分将不会执行,仅返回nil而不是抛出错误。

更多阅读内容:http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

答案 1 :(得分:1)

您可以使用传统的.try

current_user.try(:role) == "admin"

或安全导航操作符,如果您使用的是红宝石&.,则速度更快>= 2.3.0

current_user&.role == "admin"