Assigning default value while creating migration file

Ruby on-RailsMigration

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

t.integer :retweets_count, :default => 0

... should work.

See the Rails guide on migrations

Solution 3 - Ruby on-Rails

Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":

class AddColumnToWidgets < ActiveRecord::Migration
  def change
    add_column :widgets, :colour, :string, default: 'red'
  end
end

This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.

Solution 4 - Ruby on-Rails

I tried t.boolean :active, :default => 1 in migration file for creating entire table. After ran that migration when i checked in db it made as null. Even though i told default as "1". After that slightly i changed migration file like this then it worked for me for setting default value on create table migration file.

t.boolean :active, :null => false,:default =>1. Worked for me.

My Rails framework version is 4.0.0

Solution 5 - Ruby on-Rails

You would have to first create your migration for the model basics then you create another migration to modify your previous using the change_column ...

def change
    change_column :widgets, :colour, :string, default: 'red'
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkxhitizView Question on Stackoverflow
Solution 1 - Ruby on-RailstaroView Answer on Stackoverflow
Solution 2 - Ruby on-RailsJitsView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMSCView Answer on Stackoverflow
Solution 4 - Ruby on-RailsMadhan AyyasamyView Answer on Stackoverflow
Solution 5 - Ruby on-RailsArtur PedrosaView Answer on Stackoverflow