Ahmed Bassiouny
Ahmed Bassiouny

Reputation: 275

Rails 4 set the default value of a existing column to zero

The question can't be explained more.

db/migrate/20140415150026_create_poll_answers.rb

class CreatePollAnswers < ActiveRecord::Migration
  def change
    create_table :poll_answers do |t|
      t.string :content
      t.integer :counter 
      t.boolean :instant_value
      t.timestamps
    end
  end
end

db/schema

create_table "poll_answers", force: true do |t|
  t.string   "content"
  t.integer  "counter"
  t.boolean  "instant_value"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "poll_question_id"
end 

I found an answer to this but I am not sure it works for rails 4 and I also don't know where I should write it !!!

add_column :Table_name, :colman_name, :data_type, :default => "default"

Upvotes: 4

Views: 5366

Answers (1)

rails4guides.com
rails4guides.com

Reputation: 1441

You can simply set defaults like this for new migrations:

create_table :poll_answers, force: true do |t|
  t.string  :content, default: 'no_text'
  t.integer :counter, default: 0
  t.float   :money_in_pocket, default: 0.0 
 end

Or you can change existing migrations like this:

def change
  change_column :poll_answers, :counter, :integer, default: 100
end

Or even shorter:

change_column_default(:poll_answers, :counter, 3000)

Upvotes: 9

Related Questions