我有一个 text_area
,如果特定对象为空、nil 或空白,我想为其设置 placeholder
属性。
我目前正在这样做:
<%= f.text_area :comment, placeholder: @response.followup ||= "Would you like to add a note?" %>
如果@response.followup
是nil
,这似乎有效,但如果它只是空......它不使用“你愿意吗?”想要添加注释吗?”
我正在设置的默认文本。
最佳答案
检查您是否有presence
在您的 Rails 版本中可用。如果是,您可以执行以下操作
<%= f.text_area :comment, placeholder: @response.followup.presence || "Would you like to add a note?" %>
如果不可用,您可以选择以下选项之一
- 使用装饰器/演示器(我认为这太过分了)
设置 Controller 中占位符的值
@response.followup = 'Would you like to add a note?' if response.blank?
在 View 中使用三元运算符
<%= f.text_area :comment, placeholder: (@response.followup.blank? ? "Would you like to add a note?" : @response.followup) %>
关于ruby-on-rails - 如果数据为空、nil 或空白,则返回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18634527/