Отношение 2 к 1 has_many через Rails (как соединить три модели вместе) - PullRequest
0 голосов
/ 04 января 2012

Как лучше всего подключить следующие три модели?

class Tournament < ActiveRecord::Base
    has_many :submissions
    has_many :creatures, :through => :submissions, :uniq => true
    has_many :teams, :through => :submissions, :uniq => true
end

class Creature < ActiveRecord::Base  
    belongs_to :team
    has_many :tournaments, :through => :team
end

class Submission < ActiveRecord::Base
    belongs_to :tournament
    belongs_to :team
end

class Team < ActiveRecord::Base
    has_many :creatures
    has_many :submissions
    has_many :tournaments, :through => :submissions
end

Я хочу добиться чего-то подобного:

> team_1.tournaments[0] = tournament_1

> tournament_1.teams[0]
 (returns team_1)

> team_1.tournaments[0].creatures
 (returns [])

> team.tournaments[0].creatures[0] = creature_1

> creature_1.tournaments 
 (returns tournament_1)

Какой самый эффективный способ получитьконкретное существо и команда, связанная с определенным турниром?

РЕДАКТИРОВАТЬ: Выше приведено желаемое поведение. Текущая проблема заключается в том, что, как только я добавляю команду в турнир.турнир указан в creature.tournament, а я пытаюсь сделать так, чтобы существа добавлялись в турнир выборочно. Возможно ли это вообще с одним столом соединения?

Спасибо!

1 Ответ

0 голосов
/ 04 января 2012

Отправка должна быть вашей таблицей соединения между Tournaments и Teams, верно?

             Creature [id, team_id]
                             |
                             |
                             |
                       Team [id]
                             |
                             |
                             |
           Submission [id, team_id, tournament_id]  
                                          |
                                          |
                                          |
                              Tournament [id]

Модельные отношения:

class Creature < ActiveRecord::Base  
  belongs_to :team
  has_many :tournaments, :through => :team   # this should work since Rails 3.1 or 3.2
end

class Team < ActiveRecord::Base  
  has_many :creatures 
  has_many :tournaments, :through => :submissions
  has_many :submissions
end

class Submission < ActiveRecord::Base  
  belongs_to :team
  belongs_to :tournament
end

class Tournament < ActiveRecord::Base  
  has_many :teams, :through => :submissions
  has_many :creatures, :through => :teams     # this should work since Rails 3.1 or 3.2
  has_many :submissions
end

Теперь вы сможете звонить: team_1.tournaments[0].creatures

...