Rails 单行 if else 语句 [英] Rails single line if else statement
本文介绍了Rails 单行 if else 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在视图中编写一行 if else 语句.
I'm trying to write a single line if else statement in a view.
<%= collection.name ? collection.name : @miniature.name %>
如果存在 collection.name,我希望它放,否则我希望它放 @miniature.name
I want it to put collection.name if one exists, otherwise I want it to put @miniature.name
推荐答案
为了更清楚,你可以使用逻辑 OR
和 ActiveSupport's
Object#presence
(仅在 collection.name
存在且不为空时才放入):
To make it even clearer, you can use logical OR
and ActiveSupport's
Object#presence
(to put collection.name
only if it exists and isn't blank):
<%= collection.name.presence || @miniature.name %>
如果你想显示 collection.name
如果它不是 nil
,但它是空白的(空字符串或只包含空格的字符串),它就足够了:
If you want to display collection.name
if it's not nil
, but it's blank (empty string or string containing only whitespace), it will be enough to have:
<%= collection.name || @miniature.name %>
这篇关于Rails 单行 if else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文