Richard
Richard

Reputation: 16742

How do you automatically add foreign keys to an existing Rails database?

I'm new to Ruby, and joining an existing Ruby on Rails project trying to understand the database to rearchitect it.

If I generate a MySql diagram I see that Rails doesn't use foreign keys, making it impossible to analyse the diagram: enter image description here

But Ruby understand table relationships obviously internally. Is there any script that can go through all the migrations .rb scripts and add foreign keys to them automatically?

Upvotes: 2

Views: 1059

Answers (2)

max
max

Reputation: 101811

The statement "Rails doesn't use foreign keys" is simply not true.

ActiveRecord does not require you to use foreign keys constraints for associations. It does however add foreign key constraints by default when you use the references and belongs_to migration macros.

rails g model thing other_thing:references

So if you are taking over a legacy project with no or little referential integrity that is the developers fault - not Rails. Don't blame the hammer when the carpenter is drunk.

Understanding when and how to use indices and constraints is actually quite difficult and building automation to do that may be an order of magnitude more complex than actually solving the task in the first place.

What you need to is actually look at the schema and models and see where the foreign keys should be added and create migrations to add those foreign keys.

Upvotes: 1

Jeff van Aswegen
Jeff van Aswegen

Reputation: 26

Add the immigrant gem found at https://github.com/jenseng/immigrant to your Gemfile and then

rails generate immigration AddKeys
rake db:migrate

You will also need to include the foreigner gem if you are using an older version of Rails.

Upvotes: 1

Related Questions