【发布时间】:2021-10-31 09:39:56
【问题描述】:
我有以下型号:
class League < ApplicationRecord
has_many :games
end
class Game < ApplicationRecord
belongs_to :league
end
在我的用户 show.html.erb 中,我试图通过这个 sn-p game.league.title 显示用户的游戏和与游戏相关的联赛,这是视图:
<div class="hidden text-center" id="tab-settings">
<% current_user.games.each do |game| %>
<ul>
<li class="w-1/2 mb-4 text-left border-2 rounded-md border-coolGray-900">
<p class=""><%= game.start_time&.strftime("%a %b %d, %Y %l:%M%P") %> - <%= game.end_time&.strftime("%l:%M%P") %></p>
<p class="mb-2"><%= game.league.title %> - <%= game.home_team %> vs <%= game.away_team %></p>
</li>
</ul>
<% end %>
</div>
game.league.title 返回undefined method "title" for nil:NilClass 错误;但是,当我进入控制台时,game.league.title 完美查询。
按照here 给出的建议,我在视图中尝试了以下操作:
<p class="mb-2"><%= game.league.try(:title) %> etc...</p>
而且效果很好。
为什么game.league.try(:title) 工作但game.league.title 返回错误?
【问题讨论】:
标签: ruby-on-rails postgresql associations has-many belongs-to