Created
September 2, 2014 20:02
-
-
Save avifoxi/895e8fe1504597d6546e to your computer and use it in GitHub Desktop.
AR one page associations workout
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
require 'active_record' | |
require 'minitest/autorun' | |
require 'minitest/spec' | |
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" | |
ActiveRecord::Migration.create_table :users do |t| | |
t.string :name | |
end | |
ActiveRecord::Migration.create_table :teams do |t| | |
t.string :name | |
t.belongs_to :coach | |
end | |
ActiveRecord::Migration.create_table :playerships do |t| | |
t.references :user | |
t.references :team | |
end | |
ActiveRecord::Migrator.up "db/migrate" | |
class User < ActiveRecord::Base | |
has_many :playerships | |
has_many :teams, through: :playerships | |
has_many :coached_teams, foreign_key: :coach_id, class_name: 'Team' | |
end | |
class Team < ActiveRecord::Base | |
has_many :playerships | |
has_many :players, through: :playerships, source: :user | |
belongs_to :coach, class_name: "User" | |
end | |
class Playership < ActiveRecord::Base | |
belongs_to :user | |
belongs_to :team | |
end | |
User.create(name: 'Avi') | |
User.create(name: 'coach') | |
Team.create(name: 'team butt!') | |
Team.first.players | |
Team.first.players << User.first | |
Team.first.coach = User.last | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment