在定义可空字段和外键时在Rails中的脚手架

时间:2021-10-27 17:01:21

I'm just figuring out my way around rails but I need a little help with the rails generate scaffold command.

我只是在摸索如何绕过rails,但是我需要一些rails生成scaffold命令的帮助。

Here's the command that I'd like to use

这是我想使用的命令

rails generate scaffold Expense user:??? name:string description:text

I'd like the description field to be nullable and the users field to be linked to another Model — in this case I'd like to create a foreign key to the Users. I'm using the devise authentication framework.

我希望description字段可以为nullable,而users字段可以链接到另一个模型——在本例中,我希望为用户创建一个外键。我使用的是设计验证框架。

I've read that many RoR developers try and avoid the scaffolding method and opt for the manual approach instead but my web-app is quite simple and I've thought of going the scaffolding way.

我读过许多RoR开发人员试图避免使用搭建方法,而选择使用手工方法,但我的web应用程序非常简单,我曾考虑采用搭建方法。

1 个解决方案

#1


6  

Scaffolding only generates the migration that you then run. Once the file is generated simply crack open the generated migration and adjust any of the values you need specific constraints on. By default columns are set to null unless you specify otherwise e.g.:

脚手架只生成随后运行的迁移。生成文件后,只需打开生成的迁移并调整所需的任何值。默认情况下,列被设置为null,除非您指定了其他值,例如:

  create_table "slugs", :force => true do |t|
    t.integer  "sequence",                     :default => 1, :null => false
    t.string   "sluggable_type", :limit => 40
    t.string   "scope",          :limit => 40
    t.datetime "created_at"
  end

This is the code generated by the friendly_id plugin as you can see they have specified that the sequence column cannot be null while the other fields have other constraints.

这是由friendly_id插件生成的代码,您可以看到,它们指定序列列不能为null,而其他字段具有其他约束。

#1


6  

Scaffolding only generates the migration that you then run. Once the file is generated simply crack open the generated migration and adjust any of the values you need specific constraints on. By default columns are set to null unless you specify otherwise e.g.:

脚手架只生成随后运行的迁移。生成文件后,只需打开生成的迁移并调整所需的任何值。默认情况下,列被设置为null,除非您指定了其他值,例如:

  create_table "slugs", :force => true do |t|
    t.integer  "sequence",                     :default => 1, :null => false
    t.string   "sluggable_type", :limit => 40
    t.string   "scope",          :limit => 40
    t.datetime "created_at"
  end

This is the code generated by the friendly_id plugin as you can see they have specified that the sequence column cannot be null while the other fields have other constraints.

这是由friendly_id插件生成的代码,您可以看到,它们指定序列列不能为null,而其他字段具有其他约束。