Topic: how to display data as yes/no for an int

I am using a check_box on a _form that is being used to save data for a complete_flag field in one of my tables.  The data is being saved to the database as an int (ie. 0 or 1) as I expected. this is okay for my edit.rhtml as i have a checkbox that can be used to modify this field accordingly.  However, my list.rhtml is displaying the actual data in the table and hence shows up on the screen as 0 or 1.

I want to be able to modify my list.rhtml file so that this complete_flag field will show values of yes/no instead of 0/1. Is there an easy way to do this translation?

Re: how to display data as yes/no for an int

In your view you can do something like this.

<%= your_one_or_zero_variable ? "yes" : "no" %>

Which is the same thing as

if your_one_or_zero_variable
  yes
else
  no
end

Re: how to display data as yes/no for an int

The possible solution is to use collect method on your list object:

   @somelist = Someobject.find_all  #Here you get the list from database
   @somelist = @somelist.collect do |item|
      # Modify each item of the collection
      if item.complete_flag == 1
         item.complete_flag = 'yes'
      else
         item.complete_flag = 'no'
      end

      # Return item back to the collection
      item
   end


This worked for me

Shoot goes down the hill

Re: how to display data as yes/no for an int

Thank you both!

Re: how to display data as yes/no for an int

dahuk wrote:

In your view you can do something like this.

<%= your_one_or_zero_variable ? "yes" : "no" %>

Which is the same thing as

if your_one_or_zero_variable
  yes
else
  no
end

Question about this: I tried using this solution but it doesn't do exactly what I want. It looks like the ruby code is actually evaluating if the field is true (ie, meaning there is some value there), then it sets it to "yes", else it sets it to "no".  What i want is to check whether the variable is 1, then set it to yes, else set it to no.  Is there a way to expand this logic in the view to do what i need?

Re: how to display data as yes/no for an int

Are you doing this on a column in a database/model? You can put a question mark at the end of the method call to return true/false depending on if the value is 1/0. For example, instead of this:

<%= @project.active ? "yes" : "no" %>

Do this:

<%= @project.active? ? "yes" : "no" %>

Otherwise, if it's not an active record attribute, you can do this:

<%= some_value.zero? ? "no" : "yes" %>

Railscasts - Free Ruby on Rails Screencasts

Re: how to display data as yes/no for an int

Thanks so much Ryan!