Ruby-on-rails 我可以将默认值传递给 rails 生成迁移吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24565589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:45:41  来源:igfitidea点击:

Can I pass default value to rails generate migration?

ruby-on-railsruby-on-rails-3rails-migrations

提问by Leantraxxx

I want to know if I can pass a default valueto the rails g migrationcommand. Something like:

我想知道是否可以将默认值传递给rails g migration命令。就像是:

 $ rails generate migration add_disabled_to_users disabled:boolean:false #where false is default value for disabled attribute

in order to generate:

为了生成:

class AddDisabledToUsers < ActiveRecord::Migration
  def change
    add_column :users, :disabled, :boolean, default: false
  end
end

采纳答案by Benj

You can't: https://guides.rubyonrails.org/active_record_migrations.html#column-modifiers

你不能:https: //guides.rubyonrails.org/active_record_migrations.html#column-modifiers

null and default cannot be specified via command line.

不能通过命令行指定 null 和 default。

回答by Deepti Kakade

Rails migration generator does not handle default values, but after generation of migration file you should update migration file with following code

Rails 迁移生成器不处理默认值,但在生成迁移文件后,您应该使用以下代码更新迁移文件

add_column :users, :disabled, :boolean, default: false

you can also see this link - http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

你也可以看到这个链接 - http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

回答by Subhash Chandra

Default migration generator in Rails does not handle default values, there is no way around as of now to specify default value defined through terminal in rails migration.

Rails 中的默认迁移生成器不处理默认值,目前还没有办法在 rails 迁移中指定通过终端定义的默认值。

you would like to follow below steps in order to achieve what you want

你想按照以下步骤来实现你想要的

1). Execute

1)。执行

$ rails generate migration add_disabled_to_users disabled:boolean

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

2)。通过编辑创建的新迁移文件将新列值设置为 TRUE/FALSE。

class AddDisabledToUsers < ActiveRecord::Migration
  def change
    add_column :users, :disabled, :boolean, default: false
  end
end

3). Run above generated migration by Executing.

3)。通过执行运行上面生成的迁移。

$ rake db:migrate

回答by Andrew Grimm

Rails 3.2 does not seem to support any kind of command line type modifier based on http://guides.rubyonrails.org/v3.2/migrations.html

Rails 3.2 似乎不支持任何基于http://guides.rubyonrails.org/v3.2/migrations.html的命令行类型修饰符

The documentation for Rails 4.1 refers to type modifiersbut the documentation for Rails 3.2does not mention the word "modifier" in the page.

Rails 4.1 的文档提到了类型修饰符,Rails 3.2的文档在页面中没有提到“修饰符”这个词。