使用 Rails 在视图中显示来自数据库的布尔值

Displaying boolean values from database in the view with Rails

所以我的数据库中有这个 table 充满布尔值,我希望能够在我的一个视图中显示它们,但不是简单的 "true" 或 "false" 字符串,这是默认值。我是 Rails 的新手,所以我不知道该怎么做。理想情况下,如果可能的话,我会将其显示为用户无法编辑的复选框(因为这是我的显示视图)。但实际上我对任何非默认设置持开放态度。有什么想法吗?

这可以通过使用助手来实现。 “?”之后的第一个参数是真实情况;错误的情况遵循“:”。

下面的示例使用字形,因为您提到想要一个复选标记,但您可以插入 "Yes" 和 "No" 或您想要的任何字符串或 html。

def bool_to_glyph(value)
      value ? "<span class='glyphicon glyphicon-ok' aria-hidden='true'></span>".html_safe : "<span class='glyphicon glyphicon-remove' aria-hidden='true'></span>".html_safe"
end

要显示结果,请在您的视图中调用

<%= bool_to_glyph(table_boolean_value) %>

注意:对于简单的字符串显示,如 "yes" 和 "no" 您不需要调用 html_safe.

value ? "yes" : "no"

已编辑:辅助方法

辅助方法包含在 app/helpers/[modelnameplural]_helper.rb

module ExamplesHelper

def bool_to_glyph(value)
      value ? "<span class='glyphicon glyphicon-ok' aria-hidden='true'></span>".html_safe : "<span class='glyphicon glyphicon-remove' aria-hidden='true'></span>".html_safe"
end

end

如果您希望所有控制器都可以使用帮助程序,请将方法添加到应用程序_helper.rb。