Create column with database migration in rails
I need to add a new column to my users table in the database. I want the column type to be set. The column represents the gender of the user. The kit should contain two options. One form is Masculine "m" and the other is for "f".
But I haven't found any documentation for adding a column with a given type.
How can i do this?
a source to share
I think you want to add gender column with default datatype (correct me if i'm wrong), if so then there will be a step
here I am assuming "M" for men and "F" for women (you can use whole numbers if you like)
create migration
ruby script/generate migration add_gender_column_to_users
This will create a migration for you, and as the name suggests, it will add a gender column to your users table.
in your migration action self.up add this
add_column :users, :gender, :string, :default => 'm'
here it says we add columns with full rows and its defaults are "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 execute
rake db:migrate
thats it, hope this helps
a source to share