Skip to content

Instantly share code, notes, and snippets.

@memaker
Last active April 7, 2017 19:30
Show Gist options
  • Save memaker/2fa7e83adc735c16aeb824016c324b16 to your computer and use it in GitHub Desktop.
Save memaker/2fa7e83adc735c16aeb824016c324b16 to your computer and use it in GitHub Desktop.
has_many through
# using has_many :through
rails g model mountain name
rails g model climber name
rails g model adventure climber:references mountain:references
class Climber < ApplicationRecord
has_many :adventures
has_many :mountains, :through => :adventures
end
class Mountain < ApplicationRecord
has_many :adventures
has_many :climbers, :through => :adventures
end
class Adventure < ApplicationRecord
belongs_to :climber
belongs_to :mountain
end
$ 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