Ruby on Rails 生成模型字段:类型 - 字段:类型有哪些选项?
Ruby on Rails 生成模型字段:类型 - 字段:类型有哪些选项?
我正在尝试生成一个新模型,但忘记了引用另一个模型的ID的语法。我会自己查找,但是在所有我的Ruby on Rails文档链接中,我还没有找到如何找到确定的源。
$ rails g model Item name:string description:text
(然后是reference:product
或references:product
)。但更好的问题是我在未来如何查找这种傻事的代码?
注意:我已经吃过这种苦头,如果我打错了其中一个选项并运行我的迁移,那么Ruby on Rails将完全破坏我的数据库......并且rake db:rollback
对这种问题是无能为力的。 我相信我只是没有理解某些东西,但在我理解之前......由rails g model
返回的“详细”信息仍然让我郁闷......
admin 更改状态以发布 2023年5月21日
要创建引用另一个模型的模型,请使用 Ruby on Rails 模型生成器:
$ rails g model wheel car:references
这将生成 app/models/wheel.rb:
class Wheel < ActiveRecord::Base belongs_to :car end
并添加以下迁移:
class CreateWheels < ActiveRecord::Migration def self.up create_table :wheels do |t| t.references :car t.timestamps end end def self.down drop_table :wheels end end
运行迁移后,以下内容将出现在您的 db/schema.rb中:
$ rake db:migrate create_table "wheels", :force => true do |t| t.integer "car_id" t.datetime "created_at" t.datetime "updated_at" end
至于文档,Rails 生成器的起点是Ruby on Rails:指南到Rails命令行,它将指向API文档了解更多可用的字段类型。
:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references
请查看表定义部分。