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?

+2


a source to share


3 answers


What db is used? MySQL? If you want to use the SET datatype you have to do it manually as rails doesn't support it. However, I would do just

t.string :gender, :limit => 1

      



for convenience.

+7


a source


In the Your Users model, you must add the following line to require M / F responses.



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

      

+3


a source


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

+1


a source







All Articles