Skip to content

Instantly share code, notes, and snippets.

@luchiago
Last active June 20, 2020 22:55
Show Gist options
  • Save luchiago/a306526e56a26f2d260b2f68701c2667 to your computer and use it in GitHub Desktop.
Save luchiago/a306526e56a26f2d260b2f68701c2667 to your computer and use it in GitHub Desktop.
Migration for multiple foreign keys with the same model in Rails 6
class CreateMeetings < ActiveRecord::Migration[6.0]
def change
create_table :meetings do |t|
t.datetime :starts_at, null: false
t.datetime :ends_at, null: false
t.references :available_user, null: false
t.references :requester_user, null: false
t.timestamps
end
end
end
class Meeting < ApplicationRecord
belongs_to :available_user, class_name: 'User'
belongs_to :requester_user, class_name: 'User'
end
class User < ApplicationRecord
has_many :available_user_meetings, class_name: 'Meeting', foreign_key: 'available_user_id'
has_many :requester_user_meetings, class_name: 'Meeting', foreign_key: 'requester_user_id'
end
@luchiago
Copy link
Author

luchiago commented Jun 12, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment