在rails上的ruby中创建新表

Eum*_*ndi 16 ruby database ruby-on-rails create-table

我尝试在rails中创建一个新表.我找到并尝试遗忘的每个例子都不能与我合作...所以这就是我到现在为止所尝试的:(我使用Ruby版本1.9和Rails版本3.2.13在终端中创建一个新模型:

rails generate model content content_id:auto-generated, law_id:integer, parent_id:integer, titel:string, text:string, content:string, url:string
Run Code Online (Sandbox Code Playgroud)

生成以下代码:

class CreateContents < ActiveRecord::Migration
  def change
    create_table :contents do |t|
      t.auto-generated, :content_id
      t.integer, :law_id
      t.integer, :parent_id
      t.string, :titel
      t.string, :text
      t.string, :content
      t.string :url

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

如果我尝试rake db:migrate我收到以下错误消息:

 syntax error, unexpected ',', expecting keyword_end
      t.auto-generated, :content_id
                       ^
Run Code Online (Sandbox Code Playgroud)

如果我删除","我收到此错误消息:

syntax error, unexpected tSYMBEG, expecting keyword_do or '{' or '('
      t.auto-generated :content_id
                        ^
Run Code Online (Sandbox Code Playgroud)

我的研究让我也想到了这种创建表的方式:

class CreateContents < ActiveRecord::Migration
  def change
    create_table :contents do |t|
      t.auto-generated "content_id"
      t.integer "law_id"
      t.integer "parent_id"
      t.string "titel"
      t.string "text"
      t.string "content"
      t.string "url"

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用该示例来搜索数据库,我会收到以下错误消息:

syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
      t.auto-generated "content_id"
                        ^
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Luí*_*lho 18

auto-generated 不是受支持的列类型.

Active Record支持以下数据库列类型:

:binary
:boolean
:date
:datetime
:decimal
:float
:integer
:primary_key
:string
:text
:time
:timestamp
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请访问http://guides.rubyonrails.org/migrations.html#supported-types

Rails会自动为您创建列ID,因此只需将您的迁移编辑为以下内容即可

class CreateContents < ActiveRecord::Migration
  def change
    create_table :contents do |t|
      t.integer "law_id"
      t.integer "parent_id"
      t.string "titel"
      t.string "text"
      t.string "content"
      t.string "url"

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)