Rails single line if else statement

2020-02-26 04:56发布

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

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

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

3条回答
Root(大扎)
2楼-- · 2020-02-26 05:26

Check for the presence of collection.name first.

<%= collection.name.present? ? collection.name : @miniature.name %>
查看更多
forever°为你锁心
3楼-- · 2020-02-26 05:34

Couldn't you have

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

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

查看更多
虎瘦雄心在
4楼-- · 2020-02-26 05:36

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 %>

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 %>
查看更多
登录 后发表回答