Create new Table in ruby on rails

孤人 提交于 2019-12-05 11:10:35

问题


I try to create a new table in rails. Every example I find and try sadly does not work with me... so that's what I tried till now: (I use Ruby version 1.9 and Rails Version 3.2.13 making a new model in the terminal:

rails generate model content content_id:auto-generated, law_id:integer, parent_id:integer, titel:string, text:string, content:string, url:string

that generated following code:

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

if I try to rake db:migrate i get the following error message:

 syntax error, unexpected ',', expecting keyword_end
      t.auto-generated, :content_id
                       ^

if I remove the "," I get this error message:

syntax error, unexpected tSYMBEG, expecting keyword_do or '{' or '('
      t.auto-generated :content_id
                        ^

my research got me to also to this way of creating a table:

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

if I try to rake the db with that example I get this error message:

syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
      t.auto-generated "content_id"
                        ^

What do I do wrong?


回答1:


auto-generated is not a supported column type.

Active Record supports the following database column types:

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

More info in http://guides.rubyonrails.org/migrations.html#supported-types

Rails will create the column id automatically for you, thus just edit your migration to the following

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



回答2:


As others say, :auto-generated is not a supported column type. Also, it is not a symbol, it's an expression and it is parsed as :auto - generated.




回答3:


Don't put commas in your command line call to the rails generator, that's what puts those commas in your migration.



来源:https://stackoverflow.com/questions/16388756/create-new-table-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!