Rails migration using add_foreign_key: "column_ user_id", a link to an external key constraint does not exist "

(Rails - version 5.0.0, Ruby 2.3.0p0)

I want to create a relationship between the My Users table and Cards. I added belongs_to :userto the "Maps" has_many :cardsmodel and to the "Users" model and created a migration using:

class AddUserIdToCard < ActiveRecord::Migration[5.0]
  def change
    add_foreign_key :cards, :users, column: :user_id
  end
end

When I start rake db:migrate, I get an error message:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "user_id" referenced in foreign key constraint does not exist
: ALTER TABLE "cards" ADD CONSTRAINT "fk_rails_8ef7749967"
FOREIGN KEY ("user_id")
  REFERENCES "users" ("id")

Now I first worked on this problem, just adding add_column :cards, :user_id, :integerto the transfer, but this is not very indicative, and I am worried about the problems that appear later. Is there a better way to do this?

+4
source share
2

cards user_id. . , .

1    class AddUserIdToCard < ActiveRecord::Migration[5.0]
2      def change
3        add_reference :cards, :users, index:true
4        add_foreign_key :cards, :users
5      end
6    end

3 cards id users ( user_id cards).

4 user_id .

. Rails 4

+3

Rails 5. add_reference , , :

    class AddUserIdToCard < ActiveRecord::Migration[5.0]
      def change
        add_reference :cards, :users, foreign_key: true
      end
    end
0

Source: https://habr.com/ru/post/1650215/


All Articles