tva*_*nt2 153 migration ruby-on-rails-3
我在这里看到了一些关于向现有列添加默认布尔值的问题(即这一个).所以我尝试了这个change_column建议,但我一定不能做得对.
我试过了:
$ change_column :profiles, :show_attribute, :boolean, :default => true
Run Code Online (Sandbox Code Playgroud)
哪个回报 -bash: change_column: command not found
然后我跑了:
$ rails g change_column :profiles, :show_attribute, :boolean, :default => true
Run Code Online (Sandbox Code Playgroud)
...和
$ rails change_column :profiles, :show_attribute, :boolean, :default => true
Run Code Online (Sandbox Code Playgroud)
然后跑了rake db:migrate,但价值:show_attribute仍然存在nil.在我上面提到的问题中,它在PostgreSQL中说你需要手动更新它.由于我正在使用PostgreSQL,因此我在create_profiles迁移中添加了以下内容:
t.boolean :show_attribute, :default => true
Run Code Online (Sandbox Code Playgroud)
谁能告诉我这里我做错了什么?
Rob*_*bin 305
change_column是一种方法ActiveRecord::Migration,所以你不能在控制台中调用它.
如果要为此列添加默认值,请创建新的迁移:
rails g migration add_default_value_to_show_attribute
然后在创建的迁移中:
# That's the more generic way to change a column
def up
change_column :profiles, :show_attribute, :boolean, default: true
end
def down
change_column :profiles, :show_attribute, :boolean, default: nil
end
Run Code Online (Sandbox Code Playgroud)
然后跑rake db:migrate.
它不会改变已创建的记录.要做到这一点,你必须创建一个rake task或只是进入rails console并更新所有记录.
当您添加t.boolean :show_attribute, :default => true到create_profiles迁移时,如果它没有执行任何操作,这是正常的.仅执行尚未运行的迁移.如果您从一个新数据库开始,那么它将默认设置为true.
Seb*_*yet 94
作为已接受答案的变体,您还可以change_column_default在迁移中使用该方法:
def up
change_column_default :profiles, :show_attribute, true
end
def down
change_column_default :profiles, :show_attribute, nil
end
Run Code Online (Sandbox Code Playgroud)
fbe*_*ger 31
我不确定这是什么时候编写的,但是目前要在迁移中添加或删除列中的默认值,您可以使用以下命令:
change_column_null :products, :name, false
Run Code Online (Sandbox Code Playgroud)
Rails 5:
change_column_default :products, :approved, from: true, to: false
Run Code Online (Sandbox Code Playgroud)
http://edgeguides.rubyonrails.org/active_record_migrations.html#changing-columns
Rails 4.2:
change_column_default :products, :approved, false
Run Code Online (Sandbox Code Playgroud)
http://guides.rubyonrails.org/v4.2/active_record_migrations.html#changing-columns
这是一种避免查看列规范的迁移或模式的简洁方法.
| 归档时间: |
|
| 查看次数: |
119057 次 |
| 最近记录: |