Reputation: 479
Before I ask my question, I will give some context.
In my Rails 4 app, I have 3 models in question.
Clubs has_many Teams.
Teams belong_to Clubs
Clubs has_many Schedules.
Schedules belong_to Clubs.
The Relevant Columns for Teams in the Database:
:win(integer)
:loss(integer)
:tie(integer)
The Relevant Columns for Schedules in the Database:
:team1
:team2
The schedule object is supposed to show 2 teams versus each other. In the form for the schedule object, I will make
Club.teams available in 2 separate drop-down boxes, so the user can select :team1
and :team2
.
Upon the creation of a Schedule object, I'd like to make a toggle box available which you can click on later to state which team won the match.
Example Setup for the div of a Schedule Object:
Team 1 |(Box1)|(Box2)|(Box3)| Team 2
If Box1 is clicked for example, that would mean Team 1 won and I would automatically adjust the Win/Loss/Tie Columns in the Teams Table(Increase :win by 1 for Team 1 and increase :loss by 1 for Team 2). Box2 means tie and Box2 means Team 2 won. This will be done by ajax.
Finally, for my question, how do I associate :team1
and :team2
columns in the Schedule object with the appropriate Team objects in the Teams table in order to manipulate their columns with the toggle box?
Upvotes: 1
Views: 120
Reputation: 961
Here you need to create a join table referencing the same model, which in your case is team
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
and in the TeamMatch Model you will do something like that
class TeamMatch < ActiveRecord::Base
belongs_to :team_a, :class_name => :Team
belongs_to :team_b, :class_name => :Team
end
and in the Team model
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
and you are good to go, create two teams and do something like that and see if it works in your console
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
Upvotes: 4