Change Bit Value To Text When Viewed


#1

Hey All, very simple question for you folks :wink:

I have a @commutes object that for each record there is a bit value set
(0/1) to denote if an accident occurred. What I want to do is have it
display “Yes” or “No” when I view the listing of commutes. I can get it
to
display the bit value just fine with <%= commute.accident %> but how can
I
get it so that when a record with a 0 comes up that it displays “No” and
if
a 1 “Yes”? Thanks in advance!


#2

<%= commute.accident ? “Yes” : “No” %>

Michael


#3

Perfect! That’s exactly what I needed.

Ryan


#4

Maybe you can try the Acts_as_bitfield plugin

http://wiki.rubyonrails.org/rails/pages/Acts+As+Bitfield+Plugin

Cheers!


Mathias Stjernstrom


#5

Michael T. wrote:

<%= commute.accident ? “Yes” : “No” %>

Following on to this solution: how would I go about it if I wanted to
encapsulate this logic in a method? E.g.:

<%= commute.accident.YesNo %>

Is it possible to define the method in such a way that it is available
for every boolean attribute in my model?

Thanks,
Mike


#6

Probably, and in that case you would open up the
ActiveRecord::ConnectionAdapters::Column class and add in the method,
for instance boolean_to_string. That may or may not be the right spot
for it.

Generally what I see is that you would define a helper, and use that.
For instance, in your helpers/application_helper.rb file put in
something like

def YesNo(value)
value ? “Yes” : “No”
end

Then in your view you do

<%= YesNo(commute.accident) %>

Now granted, I’m just learning this stuff, so there’s probably another
way that is a much better approach.

Michael


#7

Just to clarify:

<%= commute.accident ? “Yes” : “No” %>

Didn’t work for me, but the following did.

<%= commute.accident == 1 ? “Yes” : “No” %>

Thanks!


#8

I would think that

<%= commute.accident? ? “Yes” : “No” %>

should have also worked

Craig


#9

You might want to handle true and false different from zero and nonzero.
Rails translates bits to boolean TrueClass and FalseClass, so this code
works for me:

# Translate boolean true/false to string 'Yes' / 'No' for 

human-friendly reading
# of checkbox fields.
def handle_translations(field)
case field
when TrueClass, FalseClass
(field) ? ‘Yes’ : ‘No’
else
field
end
end

Craig W. wrote:

I would think that

<%= commute.accident? ? “Yes” : “No” %>

should have also worked

Craig