So I've got this table on my database full of boolean values and I want to be able to display them in one of my views, but not as a simple "true" or "false" string, which is the default. I am new to Rails so I don't know what to do here. Ideally I would have it displayed as a checkbox that the user cannot edit (because this is for my show view), if that's possible. But really I am open to anything that's not the default. Any ideas?
1 Answer
This can be achieved by using a helper. The first argument after the "?" is the true case; the false case follows the ":".
The example below uses glyphicons, since you mentioned wanting a check mark, but you could insert "Yes" and "No" or any string or html you desire.
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
To display the result, invoke in your view as
<%= bool_to_glyph(table_boolean_value) %>
Note: For a simple string display, like "yes" and "no" you do not need to invoke html_safe.
value ? "yes" : "no"
Edited: Helper methods
Helper methods are included under 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
If you want the helper to be available to all controllers, add the method to the application_helper.rb.
check_box_tag 'Your-column-nane', disabled: true