1

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
  • have you tried this check_box_tag 'Your-column-nane', disabled: true Commented May 26, 2015 at 18:41

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help! Now where would I add a helper method? Does it go inside a controller or somewhere specific?
I just figured it out actually! Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.