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

项目名称:字符串描述:文本(这里是reference:product或references:product)。但更好的问题是,我在哪里或如何在未来轻松地寻找这种愚蠢?

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


如果您正在尝试了解Ruby on Rails的基本知识,http://guides.rubyonrails.org应该是一个不错的网站。

这是一个在你生成模型时关联模型的链接: http://guides.rubyonrails.org/getting_started.html#associating-models

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

参见表定义部分。

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

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

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

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

要创建引用另一个模型的模型,请使用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文档以获取更多可用字段类型的信息。

在写这个命令时,请记住不要将文本大写。 例如:

写:

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