Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 475
Ahmed Bassiouny Avatar asked Jan 10 '23 19:01

Ahmed Bassiouny


1 Answers

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)
like image 97
rails4guides.com Avatar answered Jan 16 '23 19:01

rails4guides.com