Skip to content

Instantly share code, notes, and snippets.

@georgekettle
Created February 4, 2021 00:10
Show Gist options
  • Save georgekettle/22757ce6604b826b60e639821a735c35 to your computer and use it in GitHub Desktop.
Save georgekettle/22757ce6604b826b60e639821a735c35 to your computer and use it in GitHub Desktop.
ActiveRecord associations & Validations
class CreateTeams < ActiveRecord::Migration[6.0]
def change
create_table :teams do |t|
t.string :name
t.timestamps
end
end
end
class CreatePlayers < ActiveRecord::Migration[6.0]
def change
create_table :players do |t|
t.string :name
t.references :team, foreign_key: true
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :email
t.timestamps
end
end
end
class CreateLikes < ActiveRecord::Migration[6.0]
def change
create_table :likes do |t|
t.references :player, foreign_key: true
t.references :user, foreign_key: true
t.timestamps
end
end
end
class AddNameToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :first, :string
add_column :users, :last, :string
end
end
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :player
end
class Player < ActiveRecord::Base
belongs_to :team
has_many :likes
has_many :users, through: :likes
end
class Team < ActiveRecord::Base
has_many :players
end
class User < ActiveRecord::Base
has_many :likes
validates :first, :last, presence: true
validates :first, length: { minimum: 3 }
validates :email, uniqueness: true
validates :email, format: { with: /\A.*@.*\.com\z/ }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment