2013-09-07 5 views
0

У меня есть модель Match и модель Team, каждый Match имеет два teams и каждый Team может иметь несколько Matches.has_many отношения Rails Модель belongs_to

Team: name:string 

Match name:string team1:references team2:references 

Так что мои модели выглядят так.

class Match < ActiveRecord::Base 
    belongs_to :team1, :class_name => Team, :foreign_key => "team1_id" 
    belongs_to :team2, :class_name => Team, :foreign_key => "team2_id" 
end 

class Team < ActiveRecord::Base 
    has_many :matches 
end 

Я хочу, чтобы создать новую команду через матч. И я не хочу ни дублировать записи матча, ни записи команды. Я немного потерян, если эта ассоциация является правильной между Team и Match.

ответ

0

Здесь вы должны использовать has_and_belongs_to_many отношений.

Match.rb

class Match < ActiveRecord::Base 
    has_and_belongs_to_many :teams 
end 

Team.rb

class Team < ActiveRecord::Base 
    has_and_belongs_to_many :matches 
end 

и генерировать миграции для создания таблицы, чтобы связать команды и матчи друг с другом:

rails g migration create_matches_teams_table 

Затем в сгенерированной миграции файл:

class CreateMatchTeams < ActiveRecord::Migration 
    def self.up 
    create_table :matches_teams, :id => false do |t| # :id => false; is to prevent the creation of primary key 
     t.integer :match_id 
     t.integer :team_id 
    end 
    end 

    def self.down 
    drop_table :matches_teams 
    end 
end 

Затем запустите эту миграцию, и вы можете связать команды и матчи друг с другом через отношения HABTM.

+0

спасибо за ваш ответ, он работает до сих пор :), так что даже при том, что матч может иметь только 2 команды HABTM отношений будет одним из лучших по вашему мнению? – daiikota

0

попробовать что-то вроде этого:

class Match < ActiveRecord::Base 
    #home team 
    belongs_to :team1, :class_name => Team, :foreign_key => "team1_id" 
    #away team 
    belongs_to :team2, :class_name => Team, :foreign_key => "team2_id" 

    #this should only allow 1 match between each team 
    validates :team1_id, :uniqueness => { :scope => :team2_id } 
end 

class Team < ActiveRecord::Base 
    has_many :home_matches, :class_name => Match, :foreign_key => "team1_id" 
    has_many :away_matches, :class_name => Match, :foreign_key => "team2_id" 

    validates :name, :uniqueness => true 

    def matches 
    Match.where("team1_id = ? OR team2_id = ?", self.id, self.id) 
    end 
end 
Смежные вопросы