Jill
Jill

Reputation: 441

Ruby-On-Rails how to make boolean gender selection from radio button appear as string(M or F) in show.html

When creating a new user they select male of female with a radio button. When I go to the show view their gender is displayed as true or false not as male or female.

_form.html.erb
  <%= f.label :gender %><br />
 <%= f.label :gender, "Male", :value => "true"  %>
<%= f.radio_button :gender, true %>
<%= f.label :gender, "Female", :value => "false" %>
<%= f.radio_button :gender, false %>


Show.html.erb
<p>
  <strong>Gender:</strong>
  <%= @user.gender %>
</p>

Upvotes: 1

Views: 3124

Answers (1)

max
max

Reputation: 102368

Don't use a boolean to represent gender.

There are quite a few countries in the world (Australia, Germany etc) that allow you to legally have other genders than female or male. I don't want to digress into a political discussion but using booleans for anything that is not truly a boolean condition is not a good idea.

If you want a final argument why you should not use a boolean consider this:

User.find(1).gender?

What is the return value of this expression?

Instead use an enum. Which means you should use an integer column in the database.

class User < ActiveRecord::Base
  enum gender: [:undisclosed, :female, :male, :other]
end

This will let you do:

user.male?
User.female # User.where(gender: :female)
user.female! # Makes a user female.

To create radio buttons you would use:

<%= radio_button_tag(:gender, "male") %>
<%= label_tag(:gender_male,   "Male") %>
<%= radio_button_tag(:gender, "female") %>
<%= label_tag(:gender_female, "Female") %>

Upvotes: 10

Related Questions