Ruby on Rails生成模型字段:类型-字段:类型的选项是什么?

我试图生成一个新模型,并忘记引用另一个模型的ID的语法。我自己也会去查,但我还没有在所有Ruby on Rails文档链接中找到确切的源代码。

$ rails g model Item name:string description:text(这里是reference:productreferences:product)。但更好的问题是在哪里如何,我能在将来轻松地寻找这种愚蠢吗?

注意:我已经学会了一种艰难的方式,如果我错误输入这些选项中的一个和运行我的迁移,那么Ruby on Rails将完全搞砸我的数据库…而rake db:rollback对这种错误无能为力。我确定我只是有些地方不明白,但在我明白之前…rails g model返回的“详细”信息仍然让我抓挠…

215683 次浏览

http://guides.rubyonrails.org应该是一个很好的网站,如果你试图通过Ruby on Rails的基本内容。

这是一个在你生成模型时关联模型的链接: http://guides.rubyonrails.org/getting_started.html#associating-models < / p >
:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp,
:time, :date, :binary, :boolean, :references

参见表定义部分。

$ rails g model Item name:string description:text product:references

我也发现这些指南很难使用。很容易理解,但很难找到我要找的东西。

此外,我有临时项目,我运行rails generate命令。一旦我让它们工作起来,我就在我的真正项目中运行它。

以上代码的引用:http://guides.rubyonrails.org/getting_started.html#associating-models

要创建引用另一个模型的模型,请使用Ruby on Rails模型生成器:

$ rails g model wheel car:references

生成应用程序/模型/ 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文档以获取更多可用字段类型的信息。

在写这个命令时,记住不要将你的文本大写。 例如:< / p >

写:

rails g model product title:string description:text image_url:string price:decimal

不要写:

rails g Model product title:string description:text image_url:string price:decimal

至少这对我来说是个问题。

我也有同样的问题,但我的代码有点不同。

def new
@project = Project.new
end

我的表格是这样的:

<%= form_for @project do |f| %>
and so on....
<% end %>

这是完全正确的,所以我不知道怎么算出来。

最后,加入

url: { projects: :create }


<%= form-for @project ...%>


为我工作。

在ROR中创建引用other的模型非常简单。

项目名称:字符串描述:文本产品:引用

这段代码将在Item表中添加'product_id'列

有很多数据类型,你可以在创建模型时提到,一些例子是:

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references

语法:

field_type:data_type