You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails Active Record关联报错:undefined method `temp' for nil:NilClass

问题排查与解决建议
  • 确认当前@location是否存在关联记录:控制台执行Location.last.recordings.last.temp正常,说明部分Location有Recording,但代码中的@location可能是一条没有任何关联Recording的记录。可以在代码中先判断:

    if @location.recordings.present?
      json.temp @location.recordings.last.temp
    else
      json.temp nil # 或设置默认值
    end
    

    或者使用Ruby安全导航操作符直接避免报错:

    json.temp @location.recordings.last&.temp
    
  • 检查代码执行上下文:若代码在回调、初始化或事务未提交的场景中运行,可能此时关联的Recording还未持久化到数据库,导致last返回nil。需确保Recording已成功保存后再访问该属性。

  • 预加载关联数据:如果@location是通过控制器查询得到的,建议使用includes预加载关联的Recording,避免延迟加载时出现数据不一致:

    @location = Location.includes(:recordings).find(params[:id])
    

内容的提问来源于stack exchange,提问作者Wrest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 13:45:28