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.
- 我是否正確定義了模型關聯?
- 當我創建或編輯團隊時,如何爲團隊分配球員或隊長?
任何幫助將不勝感激。
我有興趣瞭解定義這些模型和關聯的不同方式。因爲說實話,所有這些belongs_to和has_many的東西真的讓我困惑。 – Ramin 2010-11-11 23:03:05
例如,您可以不將船長定義爲has_one,而是將其作爲名冊模型的屬性。但在這種情況下使用has_one似乎很好。 – 2010-11-12 07:33:21