I am working on a Rails application where I need to add some of the Foreign keys for existing columns from Rails migrations and few people working on same as well. I am adding this way:
class AddUserRefToEvents < ActiveRecord::Migration[5.2]
def change
add_foreign_key :events, :users, name: :index_events_on_user_id
end
end
and one of my mate is adding this way:
class AddUserToParts < ActiveRecord::Migration[5.0]
def up
add_reference :parts, :user
end
def down
remove_reference :parts, :user
end
end
When we use SchemaCrawler for building schema diagram, the relation is built in between user and events (with add_foreign_key
) but there is no relation between users and parts (when added add_reference
).
Can you tell me why? Can we use both (with reference to this link) or only add_foreign_key
? Please help.
The fact is that add_reference
does not add a foreign key by default. The API Docs for v5.2 or v5.0 state that the options hash can include a :foreign_key
key to set the appropriate foreign key constraint.
So, to use add_reference
just change your code to include foreign_key: true
as an option.
add_reference :parts, :user, foreign_key: true