如果特定对象为空,为零或空白,我有一个text_area
我想设置placeholder
属性。
我目前正在这样做:
<%= f.text_area :comment, placeholder: @response.followup ||= "Would you like to add a note?" %>
如果@response.followup
为nil
,这似乎有效,但如果它只是空的......它不会使用我设置的"Would you like to add a note?"
默认文字。
答案 0 :(得分:4)
检查您的rails版本中是否有presence
可用。如果是,您可以执行以下操作
<%= f.text_area :comment, placeholder: @response.followup.presence || "Would you like to add a note?" %>
如果不可用,您可以选择以下其中一项
设置控制器中占位符的值
@response.followup = 'Would you like to add a note?' if response.blank?
在视图中使用三元运算符
<%= f.text_area :comment, placeholder: (@response.followup.blank? ? "Would you like to add a note?" : @response.followup) %>
答案 1 :(得分:0)
您应该能够测试“空白”并使用:
placeholder: !@response.followup.blank? ? @response.followup : "Would you like to add a note?"
因此,如果后续内容不是空白,则使用它,否则使用默认文本。
答案 2 :(得分:0)
<%= 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?") %>
如果你发现读数更好。
答案 3 :(得分:0)
使用present?方法
<%= f.text_area :comment, placeholder: (@response.followup.present? ? "Would you like to add a note?" : @response.followup) %>
答案 4 :(得分:0)
我经常这样做,我不得不做这样的事情:
class Object
def fill(wtf)
present? ? self : wtf
end
end
<%= f.text_area :comment, placeholder: @response.followup.fill("Would you like to add a note?") %>
示例:
require 'active_support/core_ext/object/blank'
class Object
def fill(wtf)
present? ? self : wtf
end
end
p nil.fill("omg")