Saghir A. Khatri
Saghir A. Khatri

Reputation: 3138

assign a default value for column ruby on rails

i have created a migration for user, later on i added column to my model using

rails generate migration add_usertype_to_users usertype:string which generates following

class AddUsertypeToUsers < ActiveRecord::Migration
  def change
    add_column :users, :usertype, :string
  end
end

now i am trying to assign default value to this usertype as basic.

where it would be better to assign default to this column, i.e inside migration, inside my model, or do i have to create new migration? all the examples i came up with are giving default value at time of creating migration when creating column, please let me know the right way. Thanks in advance

Upvotes: 2

Views: 542

Answers (2)

Debadatt
Debadatt

Reputation: 6015

Setting default value in migration is better.

You can define default value like this

class AddUsertypeToUsers < ActiveRecord::Migration
  def change
    add_column :users, :usertype, :string, default: 'value'
  end
end

Upvotes: 3

amit karsale
amit karsale

Reputation: 755

add_column :users, :usertype, :string, :default => "your_text"

Upvotes: 2

Related Questions