1

I am trying to add user:references onto my already existing model. This is what I originally wrote:

rails g model Post title:string description:text

I do this to add the user:references by running rails generate migration add_user_to_posts user:references, I am receiving this error upon running rake db:migrate:

-- create_table(:users)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: table "users" already exists

I am reading the error and I understand I already have a User model, however, I want to add this attribute to the Post model, not the User model.

Db file:

Posts:

class CreatePosts < ActiveRecord::Migration[5.0]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :description

      t.timestamps
    end
  end
end

Trying to add the user to posts:

class AddUserToPosts < ActiveRecord::Migration[5.0]
  def change
    add_reference :posts, :user, foreign_key: true
  end
end

Users:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :name
      t.string :uid
      t.string :avatar_url

      t.timestamps
    end
    add_index :users, :uid
  end
end

However, rake db:migrate gives me the error above.

Benjamints
  • 849
  • 1
  • 10
  • 24
  • Possible duplicate of [Adding a column to an existing table in a Rails migration](http://stackoverflow.com/questions/4834809/adding-a-column-to-an-existing-table-in-a-rails-migration) – Eli Sadoff Nov 28 '16 at 17:33
  • Thank you for your fast response. I have written exactly what that question has told someone to do above. But it is giving me the error that 'users' already exists, above. It looks like I am running the migration correctly but when I rake db:migrate it is giving me this error. – Benjamints Nov 28 '16 at 17:36
  • Try resetting your pending migrations first then try this again. – Eli Sadoff Nov 28 '16 at 17:37
  • Same error. I have added to my post to help you. – Benjamints Nov 28 '16 at 17:41
  • Try to replace `add_reference :posts, :user, foreign_key: true` with `add_column :posts, :user_id, :integer` – Thanh Nov 29 '16 at 03:14

0 Answers0