按照什麼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
我真的要檢查Rails中的多態關聯 – Zippie
Guy,謝謝你的回答。我沒有看到這將如何工作。假設我想創建一個新的足球隊和一些足球運動員。你能幫我解決嗎?另外,怎麼樣的移民,我需要像運動類型一樣多的表?我對這個「可歸因」有點困惑。 –
編輯我的回覆。 – gmaliar