正确使用if!= nil || != “” ROR

问题描述:

重定向到city_path如果@ city.name不等于零和 “”正确使用if!= nil || != “” ROR

如果@ city.name等于 “” 也重定向到city_path。 如何解决它?

if (@city.name != nil || @city.name != "") 
     redirect_to city_path 
     else 
     render 'index' 
    end 
+0

嘿,你可以简单地检查'if(@ city.name.present?)' –

在一个符合ternary operatorblank?方法:

@city.name.blank? ? redirect_to(city_path) : render('index') 

您可以使用present?方法会同时处理nilblank

if (@city.name.present?) 
     redirect_to city_path 
     else 
     render 'index' 
    end 

您可以像使用

if @city.name.present? 
     redirect_to city_path 
     else 
     render 'index' 
    end