Rails single line if else statement

后端 未结 3 625
野性不改
野性不改 2020-12-31 04:41

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

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

I want it

相关标签:
3条回答
  • 2020-12-31 04:47

    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 %>
    
    0 讨论(0)
  • 2020-12-31 04:51

    Couldn't you have

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

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

    0 讨论(0)
  • 2020-12-31 05:08

    Check for the presence of collection.name first.

    <%= collection.name.present? ? collection.name : @miniature.name %>
    
    0 讨论(0)
提交回复
热议问题