【问题标题】:How to access Parent of belongs_to attribute如何访问 belongs_to 属性的父级
【发布时间】: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


    【解决方案1】:

    您的数据不正确。如果您希望能够调用game.league 而不会出现潜在的零错误,您需要将games.league_id 列定义为NOT NULLGame.where(league_id: nil) 会给你一个包含空值的记录列表。

    由于 Rails 5 belongs_to 默认情况下对列应用存在验证。但是,如果您使用任何规避验证的方法,这并不能防止空值潜入。或者,如果记录是在 Rails 之外创建的,或者甚至是在旧版本的 Rails 中创建的。

    如果您希望联赛可以为空,您可以使用安全导航运算符:

    <p class="mb-2"><%= game.league&.title %> etc...</p>
    

    Object#try 是一种 ActiveSupport 方法,它早于 Ruby 2.3 中引入的安全导航运算符。虽然它确实有其用途,但通常应该首选运算符。

    你也可以使用 Module#delegate:

    class Game
      # ...
      delegate :title, to: :game, allow_nil: true, prefix: true
    end
    
    <p class="mb-2"><%= game.league_title %> etc...</p>
    

    【讨论】:

    • 我是个白痴,迁移后我从来没有刷新过我的服务器......
    • 这可能发生在我们最好的人身上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2013-04-20
    • 1970-01-01
    • 2023-03-28
    • 2011-03-29
    相关资源
    最近更新 更多