2

我在爲當前正在進行的項目定義模型設計時有點困惑。與Rails的動態關聯?

這是一個運動型團隊管理應用程序,所以我可以讓來自不同運動的團隊添加球員。因爲對於每項運動我都希望爲球員儲存不同的信息,所以我想到了以下模型。

A team: 
-> has_many soccer_players 
-> has_many basketball_players 
-> ... 

但是,這似乎是重複的,我只是有很多has_many,每一種運動類型。我的問題是,由於當時用戶創建了一個團隊,他會選擇運動類型,我只需要定義一個關聯。所以如果球隊是一支足球隊,我只需要'has_many soccer_players'。

我該怎麼做?或者甚至更好,我將如何以更好的方式對此進行建模?

感謝

回答

1

按照什麼Zippie提供和你問的評論我提供了一個稍作修改的版本是什麼。

我會打破它短語,然後到Ruby類和協會, 所以如果你想讓它忠實地多態,

  • 一支球隊有很多球員
  • 一支球隊有很多團隊屬性
  • 一個玩家 許多屬性

這可能簡化我們的應用程序的某些部分。 團隊模型本身的驗證等。 你必須決定什麼是通用屬性和什麼是動態的,例如名稱,重量,高度是通用的,因爲所有玩家都有它們,所以它們可以在Player模型中,而不在Attribute模型中。

所以我們現在可以有某種東西:

class Team < ActiveRecord::Base 
    has_many :players 
    has_many :attributes, :as => :attributable 
end 

class Player < ActiveRecord::Base 
    belongs_to :team 
    has_many :attributes, :as => :attributable 
    attr_accessible :name, :weight, :height 
end 

class Attribute < ActiveRecord::Base 
    belongs_to :attributable, :polymorphic => true 
    attr_accessible :name, :value 
end 

至於你的其他問題

的你將有一個屬性表,選手一個表,基本上球隊之一。 創建一個足球隊和球員(足球=足球是嗎?)會像這樣(讓我們決定,我們已經創造了球隊):

player = Player.new 
player.name = 'Lionel Messi' 
player.attributes << Attribute.create!(:name => :playing_position, :value => :second_striker) 
@team.players << player 
@team.attributes << Attribute.create!(:name => :uefa_cups, :value => 4) 

你的遷移會是這個樣子(直接從Rails的指南採取 - 有小的改動):

class CreateAttributes < ActiveRecord::Migration 
    def change 
    create_table :attributes do |t| 
     t.string :name 
     t.string :value 
     t.references :attributable, :polymorphic => true 
     t.timestamps 
    end 
    end 
end 
+1

我真的要檢查Rails中的多態關聯 – Zippie

+0

Guy,謝謝你的回答。我沒有看到這將如何工作。假設我想創建一個新的足球隊和一些足球運動員。你能幫我解決嗎?另外,怎麼樣的移民,我需要像運動類型一樣多的表?我對這個「可歸因」有點困惑。 –

+0

編輯我的回覆。 – gmaliar

0

也許是這樣的:

團隊:

has_many :type_of_sports, :through => type_of_sport_on_team 
has_many :players, :through => types_of_sports 

type_of_sport:

has_many :teams, :through => type_of_sport_on_team 
has_many :players 

type_of_sport_on_team:

belongs_to :team 
belongs_to :type_of_sport 

球員:

belongs_to :type_of_sport 

後附加信息:

Class Player < ActiveRecord::Base 
    attr_accessible :name, :surname, :age 
end 

Class BasketballPlayer < Player 
    attr_accessible :free_throw_average 
end 

Class SoccerPlayer < Player 
    attr_accessible :penalty_scores 
end 
+0

Zippie哪來我將特定的信息存儲在特定的運動中?我的意思是,想象一下,爲了足球,我想存儲attribute_1和attribute_2,而對於籃球,我想使用類繼承來存儲attribute_3和attribute_4 –

+0

?有一名籃球運動員和足球運動員的球員以及他們自己的額外屬性的子類 – Zippie

+0

Zippie,你將如何建模這是我的問題。這實際上是我在這個問題中主要關心的問題...... –