Skip to content

Instantly share code, notes, and snippets.

@chichunchen
Created September 20, 2014 13:12
Show Gist options
  • Save chichunchen/e987a7fe6971996acbf4 to your computer and use it in GitHub Desktop.
Save chichunchen/e987a7fe6971996acbf4 to your computer and use it in GitHub Desktop.
Basketball-Box Database association
team.rb
class Team < ActiveRecord::Base
validates :name, :presence => true
has_many :players
has_many :games
end
----------------------------------------------------
player.rb
class Player < ActiveRecord::Base
after_create :set_default_association
belongs_to :team
has_one :statistic, dependent: :destroy
has_many :game_statistic, dependent: :destroy
private
def set_default_association
self.create_statistic
end
end
----------------------------------------------------
game.rb
class Game < ActiveRecord::Base
after_create :set_default_association
validates :rival, :presence => true
belongs_to :team
belongs_to :category
has_many :game_statistics
def set_default_association
# players game_statistic db create automatically
end
end
----------------------------------------------------
statistics.rb
class Statistic < ActiveRecord::Base
belongs_to :player
end
----------------------------------------------------
game_statistics.rb
class GameStatistic < ActiveRecord::Base
belongs_to :game
end
@chichunchen
Copy link
Author

  • team : 一隊有多個球員, 多個比賽
  • game : 比賽屬於球隊,並且在新增比賽時自動產生所有歸零的球員逐場數據 - game_statistics
  • player : 一個球員擁有一個記錄了歷史記錄的資料庫 - statistics

遇到困難:

新增比賽時,要能自動產生每個球員的逐場數據(game_statistic),原本是想要跟設計球員資料庫時一樣,用after_create自動將statistic生成,但是在game.rb中不知道要怎麼讓程式知道比賽中(隊伍中)有多少個球員,進而生成該隊所有成員的逐場數據資料庫。

除了以上的問題外,如果各位前輩覺得資料庫的關聯哪裡做修正會更好,也請大家指教~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment