how to set default value to column in rails while

2019-03-12 03:03发布

I am new to Model in rails. I know how to create model & how to add column to them. Now I want to set default value to a column but I am not getting that how exactly I can do it.

I generated new model

rails g model User

then added column to it

rails generate migration AddNotificationEmailToUsers notification_email:boolean

Now I want to set value of Notification column default as true. Please guide me how to write the migration for the same. Thank you!!!

4条回答
够拽才男人
2楼-- · 2019-03-12 03:40

Best approach here is to use change_column in your migration. It is advertised to change type but you can use it to attach a default to existing column.

I had

location   :integer

in schema and I wanted to default to zero, so I wrote a migration as such:

change_column :player_states, :location, :integer, :default => 0

That did the trick.

查看更多
萌系小妹纸
3楼-- · 2019-03-12 03:45

You can't do this from the command line - you'll have to edit the migration file and change the corresponding line to something like

add_column :users, :notification_email, :boolean, :default => true
查看更多
4楼-- · 2019-03-12 03:48

Frederick Cheung is correct you will need to edit the migration file for this. Just a minor update add comma after the data type before specifying the default value.

add_column :users, :notification_email, :boolean, :default => true
查看更多
5楼-- · 2019-03-12 03:59

As of now there is no way around to specify default value defined through terminal in rails migration.

you can execute below steps in order to specify default value for a column

1). Execute

$ rails generate migration AddNotificationEmailToUsers notification_email:boolean

2). Specify the new column default value to TRUE/FALSE by editing the new migration file created.

class AddNotificationEmailToUsers < ActiveRecord::Migration
  def change
    add_column :users, :notification_email, :boolean, default: true
  end
end

3).Run above generated migration by Executing.

$ rake db:migrate
查看更多
登录 后发表回答