我有两个模型Team
和Match
一个TeamMatch
关联。
class Match < ActiveRecord::Base
has_many :teams, :through => :team_matches, :source => :team
has_many :team_matches
def attend(team)
self.team_matches.create!(:team => team)
rescue ActiveRecord::RecordInvalid
nil
end
end
class Team < ActiveRecord::Base
has_many :matches, :through => :team_matches, :source => :match
has_many :team_matches
end
class TeamMatch < ActiveRecord::Base
belongs_to :match
belongs_to :team
end
如何限制Teams
可以分配给 a 的Match
数量?
编辑:
根据建议更新。m = FactoryGirl.create(:team)
,t..2 = FactoryGirl.create(:team)
1.9.3p194 :005 > m.attend(t)
(0.1ms) BEGIN
TeamMatch Exists (0.3ms) SELECT 1 AS one FROM `team_matches` WHERE (`team_matches`.`team_id` = BINARY 1 AND `team_matches`.`match_id` = 1) LIMIT 1
SQL (0.2ms) INSERT INTO `team_matches` (`match_id`, `team_id`) VALUES (1, 1)
(0.4ms) COMMIT
=> #<TeamMatch id: 1, match_id: 1, team_id: 1>
1.9.3p194 :006 > m.attend(t1)
(0.1ms) BEGIN
TeamMatch Exists (0.3ms) SELECT 1 AS one FROM `team_matches` WHERE (`team_matches`.`team_id` = BINARY 2 AND `team_matches`.`match_id` = 1) LIMIT 1
SQL (0.1ms) INSERT INTO `team_matches` (`match_id`, `team_id`) VALUES (1, 2)
(0.4ms) COMMIT
=> #<TeamMatch id: 2, match_id: 1, team_id: 2>
1.9.3p194 :007 > m.attend(t2)
(0.1ms) BEGIN
TeamMatch Exists (0.3ms) SELECT 1 AS one FROM `team_matches` WHERE (`team_matches`.`team_id` = BINARY 3 AND `team_matches`.`match_id` = 1) LIMIT 1
SQL (0.2ms) INSERT INTO `team_matches` (`match_id`, `team_id`) VALUES (1, 3)
(0.4ms) COMMIT