Skip to content

Instantly share code, notes, and snippets.

@cheesepaulo
Last active March 27, 2018 14:45
Show Gist options
  • Save cheesepaulo/8693845b9cafab00c5fe8b9a2e34ef83 to your computer and use it in GitHub Desktop.
Save cheesepaulo/8693845b9cafab00c5fe8b9a2e34ef83 to your computer and use it in GitHub Desktop.
multiple belongs_to has_one
Trip >
belongs_to :origin, class_name: 'City'
belongs_to :destiny, class_name: 'City'
City >
has_many :origins, class_name: 'Trip', foreign_key: 'origin_id'
has_many :destinys, class_name: 'Trip', foreign_key: 'destiny_id'
Migration >
class AddOriginAndDestinyToTrip < ActiveRecord::Migration[5.0]
def change
add_reference :trips, :origin, foreign_key: {to_table: :cities}
add_reference :trips, :destiny, foreign_key: {to_table: :cities}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment