Ale Ale - 3 years ago 93
Ruby Question

How to redo a migration in Rails 5 when there is a foreign key involved?

So I have a few connected problems here. So I have begun to add topic back into my app. However when I try to create a new post, I get "Topic must exist". I am not sure what is missing for this to go through specifically.

I do know that I need to somehow redo

AddTopicReferenceToBlogs migration because right now my blogs table looks like this:

create_table "blogs", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.integer "status", default: 0
t.index ["slug"], name: "index_blogs_on_slug", unique: true
end


The t.integer "topic_id" is missing.

I know I cannot rerun AddTopicReferenceToBlogs because I will get an identical.

If I try to do a rake db:migrate:down VERSION=

I get this error:

== 20170725215733 AddTopicReferenceToBlogs: reverting =========================
-- remove_reference(:blogs, :topic, {:foreign_key=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
Table 'blogs' has no foreign key for {:to_table=>"topics", :column=>"topic_id"}


By the way my Topic.rb file looks like this:

class Topic < ApplicationRecord
validates_presence_of :title
end

Answer Source

There is no quick answer to your problem, but I think what will help you is to understand that you CAN redo AddTopicReferenceToBlogs, you are just going to have to give it a different name.

This documentation speaks to that: Rails migrations with the same name

Try something like:

rails g migration add_reference_of_topic_to_blogs topic:references

That should work assuming that you haven't screwed up some other migrations in the process as well. Rails migrations can get pretty hairy if you are not sure of what you are doing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download