Migration in rails does not add foreign keys

Asked 2 years ago, Updated 2 years ago, 49 views

Migrating with rails does not show any signs of a foreign key being created in schema.rb.

* Assumptions
We are currently creating Twitter-like applications with rails, implementing the ability for users to post multiple posts.

*What I don't understand
Configuring a foreign key in the migration file is not reflected in schema.rb.
Normally, a list of foreign keys would appear at the bottom of schema.rb, but my file is not.

* Affected Files
db/migration/create_users.rb

class CreateUsers <ActiveRecord::Migration [5.2]
  def change
    create_table —users do | t |
      t.string —name
      t.string —email
      t.integer:age

      t.timestamps
    end
  end
end

db/migration/create_posts.rb

class CreatePosts<ActiveRecord::Migration [5.2]
  def change
    create_table —posts do | t |
      t.text:content, null:false
      t.references:user,foreign_key:true
      t.string:image, null:false

      t.timestamps
    end
    add_index:posts, [:user_id,:created_at]
  end
end

db/schema.rb

ActiveRecord::Schema.define(version:2019_08_17_020505)do

  create_table "posts", force: :cascade do | t |
    t.text "content", null: false
    t. integer "user_id", null: false
    t.string "image"
    t.datetime "created_at", null:false
    t.datetime "updated_at", null:false
    t.index["user_id", "created_at", name: "index_posts_on_user_id_and_created_at"
    t.index["user_id", name: "index_posts_on_user_id"
  end

  create_table "users", force: :cascade do | t |
    t.string "name", null: false
    t.string "email", null: false
    t.datetime "created_at", null:false
    t.datetime "updated_at", null:false
    t.string "password_digest", null:false
    t.string "intro", null: false
    t. boolean "admin", default: false
    t.string "image"
  end

end

*Tried
In addition, I created and migrated the following migration file, but the results did not change.

classAddUserRefToPost<ActiveRecord::Migration [5.2]
  def change
   add_foreign_key:posts,:users
  end
end

*Environment
rails 5.2

If you know the above, please let me know.

ruby-on-rails ruby

2022-09-30 10:43

1 Answers

Actually, I think the foreign key is properly attached.

I tried the database with sqlite, but I was able to check it using the following procedure.

$sqlite3db/development.sqlite3
sqlite>.schema
...
CREATE TABLE IF NOT EXISTS "posts" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "content" text NOT NULL, "user_id" integer, "image" varchar NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "CONSTRA5" CONSTRA
FOREIGN KEY ("user_id")
  REFERENCES "users" ("id")
);
...

When I looked at github, there was a similar issue.
https://github.com/rails/rails/issues/35207

As far as the comments are concerned, rails6 seems to solve the problem.


2022-09-30 10:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.