views:

47

answers:

2

I tried creating a DB migration in Rails that looked something like this:

ruby script/generate scaffold post user_id:int title:string content:text

Looking at the resulting .rb file, sure enough, I saw everything I'd entered:

class CreatePosts < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.int :user_id # there it is: user_id
      t.string :title
      t.text :content

      t.timestamps
    end
  end

  def self.down
    drop_table :posts
  end
end

But after running rake db:migrate and inspecting my database, I see that no user_id column was created. What happened, here?

+3  A: 

Because it should be t.integer, not t.int. See the docs for more details:

add_column(table_name, column_name, type, options): Adds a new column to the table called table_name named column_name specified to be one of the following types: :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean.

Skilldrick
Damn, I had a *feeling* it would be something that simple. Thanks! (I'll accept this answer in 10 minutes.)
Dan Tao
@Dan That's cool, cheers :)
Skilldrick
This has always bugged me. Why doesn't the migration raise an exception on an invalid column type?
zetetic
+2  A: 

You can also use:

t.references :user

and it will create an integer field called user_id. I personally prefer this method because it's referencing a foreign key.

Beerlington