Search code examples
ruby-on-railsrubydatabasecreate-table

Create new Table in ruby on rails


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?


Solution

  • 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