Ruby on rails 如果数据为空、为零或为空,则返回字符串?

Ruby on rails 如果数据为空、为零或为空,则返回字符串?,ruby-on-rails,Ruby On Rails,我有一个text\u区域,我想为该区域设置占位符属性,以确定特定对象是空的、零的还是空的 我目前正在这样做: <%= f.text_area :comment, placeholder: @response.followup ||= "Would you like to add a note?" %> 如果@response.followup是nil,但如果它只是空的…它不会使用“您想添加注释吗?”我正在设置的默认文本。您应该能够测试“空白”并使用: 因此,如果后续内容不是空白

我有一个
text\u区域
,我想为该区域设置
占位符
属性,以确定特定对象是空的、零的还是空的

我目前正在这样做:

<%= f.text_area :comment, placeholder: @response.followup ||= "Would you like to add a note?" %>


如果
@response.followup
nil
,但如果它只是空的…它不会使用
“您想添加注释吗?”
我正在设置的默认文本。

您应该能够测试“空白”并使用:


因此,如果后续内容不是空白的,则使用它,否则使用默认文本。

您应该能够测试“空白”并使用:

<%= f.text_area :comment, placeholder: (@response.followup.blank? ? "Would you like to add a note?" : @response.followup) %>
因此,如果后续内容不是空的,则使用它,否则使用默认文本。


<%= f.text_area :comment, placeholder: (@response.followup.blank? ? "Would you like to add a note?" : @response.followup) %>
或许

<%= f.text_area :comment, placeholder: (@response.followup.present? ? @response.followup : "Would you like to add a note?") %>

如果你觉得这样读起来更好。


或许

<%= f.text_area :comment, placeholder: (@response.followup.present? ? @response.followup : "Would you like to add a note?") %>


如果您觉得这样读起来更好。

检查您的rails版本中是否有可用的
presence
。如果是,您可以执行以下操作

<%= f.text_area :comment, placeholder: @response.followup.presence || "Would you like to add a note?" %>

如果不可用,您可以选择以下选项之一

<%= f.text_area :comment, placeholder: @response.followup.presence || "Would you like to add a note?" %>
  • 使用装饰师/演示者(我认为这太过分了)
  • 在控制器中设置占位符的值

    @response.followup=“是否要添加注释?”如果response.blank?

  • 在视图中使用三元运算符


  • 检查rails版本中是否有可用的
    presence
    。如果是,您可以执行以下操作

    <%= f.text_area :comment, placeholder: @response.followup.presence || "Would you like to add a note?" %>
    
    
    
    如果不可用,您可以选择以下选项之一

    <%= f.text_area :comment, placeholder: @response.followup.presence || "Would you like to add a note?" %>
    
  • 使用装饰师/演示者(我认为这太过分了)
  • 在控制器中设置占位符的值

    @response.followup=“是否要添加注释?”如果response.blank?

  • 在视图中使用三元运算符

  • 使用方法

    
    
    使用方法


    我经常这样做,我不得不做这样的事情:

    class Object
      def fill(wtf)
        present? ? self : wtf
      end
    end
    

    例如:

    require 'active_support/core_ext/object/blank'
    
    class Object
      def fill(wtf)
        present? ? self : wtf
      end
    end
    
    p nil.fill("omg")
    

    我经常这样做,我不得不做这样的事情:

    class Object
      def fill(wtf)
        present? ? self : wtf
      end
    end
    

    例如:

    require 'active_support/core_ext/object/blank'
    
    class Object
      def fill(wtf)
        present? ? self : wtf
      end
    end
    
    p nil.fill("omg")