我有两个模型:games
和pickems
。
以下是我对这些模型的架构:
create_table "games", force: :cascade do |t|
t.integer "week_id", limit: 4
t.integer "home_team_id", limit: 4
t.integer "away_team_id", limit: 4
t.integer "home_score", limit: 4
t.integer "away_score", limit: 4
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "season_id", limit: 4
end
create_table "pickems", force: :cascade do |t|
t.integer "user_id", limit: 4
t.integer "game_id", limit: 4
t.integer "winner_id", limit: 4
t.integer "score", limit: 4
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
游戏模型:
class Game < ActiveRecord::Base
belongs_to :home_team, class_name: 'Team'
belongs_to :away_team, class_name: 'Team'
belongs_to :week
belongs_to :season
end
Pickem模型:
class Pickem < ActiveRecord::Base
has_one :user
has_one :game
has_one :winner, class_name: 'Team'
end
在我看来,我希望显示所有没有Pickem关联的游戏。我还想在下面显示所有Pickems和相关的游戏属性。我需要从控制器调用和/或添加到模型以显示此信息?
答案 0 :(得分:1)
首先,你有
# in `pickems` table
t.integer "game_id", limit: 4
和
# in Pickem Model
class Pickem < ActiveRecord::Base
...
has_one :game
...
end
我认为对于has_one belongs_to
,您需要将foreign_key
放在games
表而不是pickems
表中,它将开始有意义。
即。
create_table "games", force: :cascade do |t|
...
t.integer "pickem_id", limit: 4
...
end
class Game < ActiveRecord::Base
...
belongs_to :pickem
...
end
现在
我想要显示所有没有关联Pickem的游戏 正在引用它
Game.where(pickem_id: nil)
一个建议
由于您的Game
模型属于Pickem
,Team
等多个模型,因此您可以改为使用Polymorphic Association。
原因:如果您的game
条记录之一属于pickem
,则其他字段将为空。
答案 1 :(得分:1)
您需要更正Games / Pickem关联,方法是将其添加到游戏模型中:
has_one :pickem
这与Pickem模型有关:
belongs_to :game
此查询将检索所有未关联Pickem的游戏:
@games_without_pickems = Game.joins(:pickem).group("games.id").having("COUNT('pickems.id') = 0").order("games.id")
更改表格引用
这将检索所有Pickems和相关的游戏信息:
@pickems = Pickem.includes(:games).all
在您看来,只需循环遍历@games_without_pickems
和@pickems
,就像这样:
<table>
<th>
<td>Week</td>
<td>Home Team</td>
<td>Away Team</td>
<td>Home Score</td>
<td>Away Score</td>
<td>Season</td>
</th>
<% @games_without_pickems.each do |game| %>
<tr>
<td><%= game.week.name %></td>
<td><%= game.home_team.name %></td>
<td><%= game.away_team.name %></td>
<td><%= game.home_score %></td>
<td><%= game.away_score %></td>
<td><%= game.season.name %></td>
</tr>
<% end %>
</table>
<table>
<th>
<td>User</td>
<td>Winner</td>
<td>Score</td>
<td>Week</td>
<td>Home Team</td>
<td>Away Team</td>
<td>Home Score</td>
<td>Away Score</td>
<td>Season</td>
</th>
<% @pickems.each do |pickem| %>
<tr>
<td><%= pickem.user.name %></td>
<td><%= pickem.winner.name %></td>
<td><%= pickem.score %></td>
<td><%= pickem.game.week.name %></td>
<td><%= pickem.game.home_team.name %></td>
<td><%= pickem.game.away_team.name %></td>
<td><%= pickem.game.home_score %></td>
<td><%= pickem.game.away_score %></td>
<td><%= pickem.game.season.name %></td>
</tr>
<% end %>
</table>
应该这样做。