Ruby on rails 如何自定义此if语句?

Ruby on rails 如何自定义此if语句?,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我想在@user.user\u profile.authority.name出现时显示“未选中”@user.user\u profile.authority.blank?为空 如何自定义此代码 控制器 像这样 if @user.profile.prefecture.blank? 'not selected' else @user.profile.prefecture.name end 像这样 if @user.profile.prefecture.blank? 'not selec

我想在
@user.user\u profile.authority.name出现时显示“未选中”@user.user\u profile.authority.blank?
为空

如何自定义此代码

控制器 像这样

if @user.profile.prefecture.blank?
  'not selected'
else
  @user.profile.prefecture.name
end
像这样

if @user.profile.prefecture.blank?
  'not selected'
else
  @user.profile.prefecture.name
end

您可以使用三元运算符,它有点冗长:

@user.profile.prefecture.blank? ? "Not selected" : @user.profile.prefecture.name
或者,如果
地区
实际上为零/不是零,则去掉
空白?

@user.profile.prefecture ? @user.profile.prefecture.name : "Not selected"
最后,您可以使用
try
| |
稍微增加一点想象力,大多数精通Ruby的开发人员都会发现这两种方法非常可读:

@user.profile.prefecture.try(:name) || "Not selected"

您可以使用三元运算符,它有点冗长:

@user.profile.prefecture.blank? ? "Not selected" : @user.profile.prefecture.name
或者,如果
地区
实际上为零/不是零,则去掉
空白?

@user.profile.prefecture ? @user.profile.prefecture.name : "Not selected"
最后,您可以使用
try
| |
稍微增加一点想象力,大多数精通Ruby的开发人员都会发现这两种方法非常可读:

@user.profile.prefecture.try(:name) || "Not selected"
更新:

1-如果对象为false、空或空白字符串,则该对象为空

2-除非条件为false,否则执行的除非语句代码

答复:

“未选择”除非@user.profile.aperty.blank

解释:@user.profile.epistry.blank?每次@user.profile.exe为false、空或空白字符串时,都将返回true,因为否定运算符将其转换为false,因此可以执行除非代码部分

这种方法对我来说非常“Ruby”,应该很容易理解。

更新:

1-如果对象为false、空或空白字符串,则该对象为空

2-除非条件为false,否则执行的除非语句代码

答复:

“未选择”除非@user.profile.aperty.blank

解释:@user.profile.epistry.blank?每次@user.profile.exe为false、空或空白字符串时,都将返回true,因为否定运算符将其转换为false,因此可以执行除非代码部分


这种方法对我来说非常“Ruby”,应该很容易理解。

这正是我想要的这正是我想要的这不起作用。它的计算结果为
“未选择”
nil
,问题需要
@user.profile.epistry.name
“未选择”
。抱歉,meagar,除非@user.profile.epistry.blank,否则此“未选择”?每次@user.profile.aperty.blank都有效?返回零最初我离开了!签名,因为复制粘贴您可以编辑它。除非有条件,否则编码-如果有条件为假,则执行代码。那么,为什么不编辑自己的帖子,并确保将来没有人必须阅读评论才能弄清楚这一点?从现在开始,它在7小时前就已经编辑好了,你为什么要与安顿抗争?Meagar至少有一个技术要点。thnx Anthon按原作编辑(它是正确的)并解释,这样人们就不知道了,因为以前的人不认为这是错误的,也不会导致混淆。这不起作用。它的计算结果为
“未选择”
nil
,问题需要
@user.profile.epistry.name
“未选择”
。抱歉,meagar,除非@user.profile.epistry.blank,否则此“未选择”?每次@user.profile.aperty.blank都有效?返回零最初我离开了!签名,因为复制粘贴您可以编辑它。除非有条件,否则编码-如果有条件为假,则执行代码。那么,为什么不编辑自己的帖子,并确保将来没有人必须阅读评论才能弄清楚这一点?从现在开始,它在7小时前就已经编辑好了,你为什么要与安顿抗争?Meagar至少有一个技术要点。thnx Anthon按原作编辑(它是正确的)并解释,这样人们就不知道了,因为以前的人不认为这是错误的,也不会导致混淆。