Last active
April 7, 2017 19:30
-
-
Save memaker/2fa7e83adc735c16aeb824016c324b16 to your computer and use it in GitHub Desktop.
has_many through
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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