Reputation: 77
I am having a hard time getting my head around the best way to set up my models and relationships in rails as I'm need to rails, mvc, and active record conventions.
Consider three tables:
users
rails generate scaffold User username:string email:string password:string
games
rails generate scaffold Game user_id:integer name:string description:string type:string
game_rosters
rails generate scaffold GameRoster user_id:integer game_id:integer level:integer status:string
Users can create games (this is the user_id field in the games table for the "owner"). The creator may or may not be in the actual game (optional record for the creator in the game_rosters table).
Each game has many users which are apart of the game (located in game_rosters).
So I am thinking I should have two relationships for the user - has_many: games
for the games they have created, and has_many: games, through: game_rosters
for the games that user is a part of..
class User < ActiveRecord::Base
has_many :game_rosters
has_many :games, through: :game_rosters
has_many :games
end
class Game < ActiveRecord::Base
has_many :game_rosters
has_many :users, through: :game_rosters
end
class GameRoster < ActiveRecord::Base
belongs_to :user
belongs_to :game
end
But I'm not sure if this is the right set up, and I can't get it working properly.. I have the above set up, and the following for trying to print results:
<p>
<strong>My Games:</strong>
<% @user.games.each do |game| %>
<br><%= game.name %>
<% end %>
</p>
<p>
<strong>Participants:</strong>
<% @game.users do |user| %>
<br><%= game.user.name %>
<% end %>
</p>
I can print the "My Games" from the has_many: games
relationship, but can't print the "Participants" from the has_many :through
relationship.
Any direction would be appreciated, thanks.
Upvotes: 0
Views: 956
Reputation: 8003
Also want to add that you should not have the same name games
for different association in the User
model. As last one is overwriting the first. Smthing like this should work.
class User < ActiveRecord::Base
has_many :owned_games, :foreign_key => "user_id", :class_name => "Game"
has_many :game_rosters
has_many :games, through: :game_rosters
end
class Game < ActiveRecord::Base
belongs_to :owner, :foreign_key => "user_id", :class_name => "Game"
has_many :game_rosters
has_many :users, through: :game_rosters
end
class GameRoster < ActiveRecord::Base
belongs_to :user
belongs_to :game
end
Accessing the associations for a user
# All the games a user is involved in
user.games
# All the games a user owns
user.owned_games
Accessing associations for a game
#All the users involved in the game
game.users
# Owner of the game
game.owner
Upvotes: 3
Reputation: 58284
Try:
<p>
<strong>Participants:</strong>
<% @game.users.each do |user| %>
<br><%= user.name %>
<% end %>
</p>
Upvotes: 1