Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning default value while creating migration file

rails generate migration AddRetweetsCountToTweet retweets_count:integer  

Ok I use above line to create migration file that automatically generates code in the generated file to add a column to a model Tweet with datatype integer. Now I want to add default value to the added column while generating the migration file. Is that possible? I googled it but couldn't find. Guys need help.

like image 374
kxhitiz Avatar asked May 29 '11 13:05

kxhitiz


People also ask

How do I change the default value in laravel migration?

In our case we are going to do second option - create new migration. If we roll back this migration, we need to remove default value from that field using migration and this is how to do it: Schema::table('photos', function (Blueprint $table) { $table->integer('order')->default(NULL)->change(); });


2 Answers

Default migration generator does not handle default values (column modifiers are supported but do not include default or null), but you could create your own generator.

You can also manually update the migration file prior to running rake db:migrate by adding the options to add_column:

add_column :tweet, :retweets_count, :integer, :null => false, :default => 0

... and read Rails API

like image 139
taro Avatar answered Oct 12 '22 20:10

taro


t.integer :retweets_count, :default => 0 

... should work.

See the Rails guide on migrations

like image 40
Jits Avatar answered Oct 12 '22 21:10

Jits