2016-04-10 40 views
1

在问我的问题之前,我会给出一些上下文。如何正确地将模型与2个不同的对象关联?(Rails 4)

在我的Rails 4应用程序中,我有3个有问题的模型。

Clubs has_many Teams. 
Teams belong_to Clubs 
Clubs has_many Schedules. 
Schedules belong_to Clubs. 

在数据库团队中相应的列:

:win(integer) 
:loss(integer) 
:tie(integer) 

在数据库中的附表中相应的列:

:team1 
:team2 

时间表对象是为了显示2队与各其他。在日程安排对象的表格中,我将在2个单独的下拉框中提供 Club.teams,因此用户可以选择:team1:team2

创建Schedule对象后,我想创建一个切换框,您可以稍后点击以指出哪个团队赢得了比赛。

的示例设置计划对象的DIV:

Team 1     |(Box1)|(Box2)|(Box3)|      Team 2 

如果BOX1点击例如,这将意味着第1组韩元,我会自动调整赢/输/队中的表构造柱(增加:1队获胜,1增加:2队失1)。 Box2表示领带,Box2表示Team 2获胜。这将由ajax完成。

最后,对于我的问题,如何将Schedule对象中的:team1:team2列与Teams表中相应的Team对象相关联,以便通过切换框来操纵它们的列?

回答

4

在这里,你需要创建一个连接表引用相同的模型,你的情况是团队

create_table "team_matches" do |t| 
    t.integer "team_a_id", :null => false 
    t.integer "team_b_id", :null => false 
    t.integer "win_or_lose" 
end 

,并在TeamMatch模型,你会做这样的事情

class TeamMatch < ActiveRecord::Base 
    belongs_to :team_a, :class_name => :Team 
    belongs_to :team_b, :class_name => :Team 
end 

,并在团队模型

class Team < ActiveRecord::Base 
     has_many :team_matches, :foreign_key => :post_a_id, :dependent => :destroy 
     has_many(:reverse_team_matches, :class_name => :TeamMatch, 
     :foreign_key => :team_b_id, :dependent => :destroy) 

     has_many :teams, :through => :team_matches, :source => :post_b 
    end 

你很好去,创建两个团队,做一些像t帽子,看看它是否在控制台

team1 = Team.create(...) #whatever your attributes put them in the create function 

team2 = Team.create(...) #whatever your attributes put them in the create function 

team1.teams << team2 
team1.team_matches #Here the record the joins team1 and team2 will appear, along with win_or_lose_attribute 

team1.team_matches.first.update(win_or_lose: 1) #or whatever value you want to specify win, tie or lose 
+0

适用于更多的说明,您可以检查这个[问题](http://stackoverflow.com/questions/2168442/many-to-many-relationship-with-the-相同型号的导轨) – amrdruid

+0

它看起来不错,也不好测试。 – 7urkm3n

+0

你好!不太熟悉连接表。这张表会替换计划表吗?另外,如果我将team_matches与俱乐部相关联,我是否只将club_id作为team_matches的外键?我想显示所有的球队比赛,例如Club.team_matches,他们只能关联到1个俱乐部。 – kpaul

相关问题