views:

161

answers:

3

Hello.

I need to add a new column to my users table in the database. I want the type of the column to be set. The column represents the users gender. There should be two options to the set. One form Male "m" and the other for Female "f". But i havent found any doccumentation for adding a column with the set type.

How can i do this?

+2  A: 

What db is used? mysql? If you're want to use SET datatype, you'll have to do it manually, as rails doesn't support it. However, I'd do just

t.string :gender, :limit => 1

for the sake of convenience.

Evgeny Shadchnev
yes, it's mysql. okay, will do that
Micke
A: 

In your Users model, you should add the following line to require M/F answers.

validates_inclusion_of :gender, :in => %w( m f M F)

Jason Noble
A: 

Hi Micke,

I think you want to add the gender column with a default datatype (correct me if I'm wrong), If so there would be the step

here I'm assuming 'M' is for male and "F" is for female (you can use integers also if you wish)

create a migration

ruby script/generate migration add_gender_column_to_users

This will create a migration for you and as the name implies it will add a gender column to your users table

in your migrations self.up action add this

add_column :users, :gender, :string, :default => 'm'

here it says we are adding a gender column of string type and its default values is 'm'

and add this to self.down events

remove_column :users, :gender

so your final migration will look something like this

class AddGenderColumnToUsers < ActiveRecord::Migration def self.up add_column :users, :gender, :string, :default => 'm' end def self.down remove_column :users, :gender end end

and do a

rake db:migrate

thats it, hope this helps

cheers sameera

sameera207