Ruby-on-rails Rails 单行 if else 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22665145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:28:40  来源:igfitidea点击:

Rails single line if else statement

ruby-on-railsruby-on-rails-4

提问by Ossie

I'm trying to write a single line if else statement in a view.

我正在尝试在视图中编写一行 if else 语句。

<%= collection.name ? collection.name : @miniature.name %>

I want it to put collection.name if one exists, otherwise I want it to put @miniature.name

如果存在,我希望它放置 collection.name,否则我希望它放置 @miniature.name

回答by Marek Lipka

To make it even clearer, you can use logical ORand ActiveSupport'sObject#presence(to put collection.nameonly if it exists and isn't blank):

为了更清楚,您可以使用逻辑ORActiveSupport'sObject#presencecollection.name仅当它存在且不为空时才放置):

<%= collection.name.presence || @miniature.name %>

If you want to display collection.nameif it's not nil, but it's blank (empty string or string containing only whitespace), it will be enough to have:

如果你想显示collection.nameif it not nil,但它是空白的(空字符串或只包含空格的字符串),它就足够了:

<%= collection.name || @miniature.name %>

回答by davegson

Check for the presence of collection.namefirst.

首先检查是否存在collection.name

<%= collection.name.present? ? collection.name : @miniature.name %>

回答by Richard Peck

Couldn't you have

你不能有

<%= collection.name ||= @minature.name %>

To those who downvoted - Set Ruby variable if it is not already defined

对于那些投反对票的人 -如果尚未定义 Ruby 变量,则设置它