2

如果特定对象为空、nil 或空白,我有一个text_area我想设置的属性。placeholder

我目前正在这样做:

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

如果@response.followupis ,这似乎有效nil,但如果它只是空的......它不使用"Would you like to add a note?"我设置的默认文本。

4

5 回答 5

4

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

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

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

  1. 使用装饰者/演示者(我认为这是矫枉过正)
  2. 在控制器中设置占位符的值

    @response.followup = 'Would you like to add a note?' if response.blank?

  3. 在视图中使用三元运算符

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

于 2013-09-05T11:05:16.207 回答
0

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

placeholder: !@response.followup.blank? ? @response.followup : "Would you like to add a note?"

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

于 2013-09-05T11:01:19.607 回答
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?") %>

如果你发现读起来更好。

于 2013-09-05T11:02:09.600 回答
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")
于 2013-09-05T11:35:26.217 回答
0

使用礼物?方法

<%= f.text_area :comment, placeholder: (@response.followup.present? ? "Would you like to add a note?" : @response.followup) %>
于 2013-09-05T11:27:48.123 回答