Alon Shmiel
Alon Shmiel

Reputation: 7121

default value to column

I run:

rails generate migration AddHidemsgColumnToPublishers hide_msg:boolean

and the next file was created:

class AddHidemsgColumnToPublishers < ActiveRecord::Migration
  def change
    add_column :publishers, :hide_msg, :boolean
  end
end

I want to set a default value into hide_msg by false.

so I tried:

rails generate migration add_default_value_to_hide_msg

class AddDefaultValueToHideMsg < ActiveRecord::Migration
  def up
    change_column :publishers, :hide_msg, :boolean, :default => false
  end

  def down
    change_column :publishers, :hide_msg, :boolean, :default => nil
  end
end

but I got errors:

rake db:migrate
==  AddHidemsgColumnToPublishers: migrating ===================================
-- add_column(:publishers, :hide_msg, :boolean, {:default=>false})
rake aborted!
An error has occurred, this and all later migrations canceled:

PG::Error: ERROR:  column "hide_msg" of relation "publishers" already exists
: ALTER TABLE "publishers" ADD COLUMN "hide_msg" boolean DEFAULT 'f'

Upvotes: 2

Views: 3998

Answers (2)

Rahul Tapali
Rahul Tapali

Reputation: 10147

rake db:migrate
==  AddHidemsgColumnToPublishers: migrating ===================================
-- add_column(:publishers, :hide_msg, :boolean, {:default=>false})

Above thing means its trying to create colimn which already exist. If you check the class name AddHidemsgColumnToPublishers . This means it trying to execute your first migration in which you don't have default value. This clearly indicates you are doing something wrong.

publishers already has column hide_msg. So check the table description in db console. If you don't have any values in hide_msg then you can manually drop the column and re-run the rake db:migrate. Or you can keep that column as it is and just create migration to add default value.

change_column_default :publishers, :hide_msg, false

Doc: http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_column_default

Upvotes: 1

gabrielhilal
gabrielhilal

Reputation: 10769

Just a suggestion.... do not set the default value in the database, as you might face some problems if you want to change it latter on.

I think it is better if you set it in your model.

before_save :set_default_high_msg
def set_default_high_msg
  self.high_msg ||= false
end

or even in your controller:

 def new
   @publisher = Publisher.new
   @publisher.high_msg ||= false
 ...
 end

Upvotes: 5

Related Questions