2010-11-11 166 views
0

我正在嘗試爲我正在處理的一個小項目組合一對模型關聯。我是Rails的新手,所以這對我來說有點混亂。Rails 3與has_many,belongs_to和模型關聯:通過

我的用例非常簡單。我有一個體育聯賽其中有很多。每個分區有很多團隊。每個團隊有一個隊長有許多玩家

現在,玩家和上尉都由班級用戶代表。唯一區別他們的是他們的角色。我正在使用CanCan來管理角色。

現在,這裏是我的模型,以及如何我已經定義的關聯:

class Division < ActiveRecord::Base 
    belongs_to :league 
    has_many :teams 
end 

class League < ActiveRecord::Base 
    has_many :divisions 
end 

class Team < ActiveRecord::Base 
    belongs_to :division 
    accepts_nested_attributes_for :division 

    has_one :captain, :class_name => "User" 
    accepts_nested_attributes_for :captain 

    has_many :rosters 
    has_many :players, :through => :rosters, :source => :user 
    accepts_nested_attributes_for :players 

    validates_presence_of :name 
    validates_uniqueness_of :name 
end 

class User < ActiveRecord::Base 
    has_many :authentications 
    has_many :rosters 
    has_many :teams, :through => :rosters 
    belongs_to :team 
end 

And here is my generated Schema file.

  1. 我是否正確定義了模型關聯?
  2. 當我創建或編輯團隊時,如何爲團隊分配球員或隊長?

任何幫助將不勝感激。

回答

0
  1. 這個定義對我來說似乎還行。還有其他的方式(當然),但這個似乎沒問題。

  2. 這種取決於你的用戶界面。隊長應該很簡單 - 執行collection_select並將其分配給captain屬性。

玩家有點棘手。通常的做法是(和你一樣)使用collection_select和html數組name(例如team[player_id][]),在你的情況下,我想你每個團隊都有一定數量的玩家,所以你只需多次顯示它(如果不是你可以使用JavaScript來爲用戶克隆它)。

+0

我有興趣瞭解定義這些模型和關聯的不同方式。因爲說實話,所有這些belongs_to和has_many的東西真的讓我困惑。 – Ramin 2010-11-11 23:03:05

+0

例如,您可以不將船長定義爲has_one,而是將其作爲名冊模型的屬性。但在這種情況下使用has_one似乎很好。 – 2010-11-12 07:33:21

相關問題