Skip to content

Instantly share code, notes, and snippets.

@memaker
Last active April 7, 2017 18:23
Show Gist options
  • Save memaker/09d26eb752ef1c87761f58f7ee8f7dc5 to your computer and use it in GitHub Desktop.
Save memaker/09d26eb752ef1c87761f58f7ee8f7dc5 to your computer and use it in GitHub Desktop.
Some command to set up a many to many relationship
# using has_and_belongs_to_many
rails g model mountain name
rails g model climber name
class Climber < ApplicationRecord
has_and_belongs_to_many :mountains
end
class Mountain < ApplicationRecord
has_and_belongs_to_many :climbers
end
# using a model...
rails g model climbers_mountains climber:references mountain:references
# ...Rails will create
class CreateClimbersMountains < ActiveRecord::Migration[5.0]
def change
create_table :climbers_mountains do |t|
t.references :climber, foreign_key: true
t.references :mountain, foreign_key: true
t.timestamps
end
end
end
# using a migration
rails g migration CreateJoinTableClimbersMountains climber mountain
# ...Rails will create this. You must uncomment one of the t.index lines
class CreateJoinTableClimbersMountains < ActiveRecord::Migration[5.0]
def change
create_join_table :climbers, :mountains do |t|
t.index [:climber_id, :mountain_id]
# t.index [:mountain_id, :climber_id]
end
end
end
# then you should execute
$ rake db:create
$ rake db:migrate (or 'rake db:migrate RAILS_ENV=test' for the test environment)
$ rails c
john = Climber.create(name: "John Doe")
udalaitz = Mountain.create(name: "Udalaitz")
john.mountains << udalaitz
===
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment