Skip to content

Instantly share code, notes, and snippets.

@avifoxi
Created September 2, 2014 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avifoxi/895e8fe1504597d6546e to your computer and use it in GitHub Desktop.
Save avifoxi/895e8fe1504597d6546e to your computer and use it in GitHub Desktop.
AR one page associations workout
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