V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
0c0c0f
V2EX  ›  Ruby on Rails

ruby on rails: no implicit conversion of nil into String

  •  
  •   0c0c0f · 2021-10-10 19:07:02 +08:00 · 2025 次点击
    这是一个创建于 900 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Controller 代码
    class CveController < ApplicationController
    def index
    @cves = Cve.all
    end

    def show
    @cve = Cve.find_by(cve_id: params[:cve_id])
    end
    end


    异常信息
    Showing app/views/cve/index.html.erb where line #3 raised:

    no implicit conversion of nil into String
    Extracted source (around line #3):

    <h1>Cve#index</h1>
    <p>Find me in app/views/cve/index.html.erb</p>
    <% @cves.each do |cve| %>
    <tr>
    <td><%= cve.cve_id %></td>
    <td><%= cve.summary %></td>

    Rails.root: /Users/admin/RubyProjects/xx-api

    Application Trace | Framework Trace | Full Trace
    app/views/cve/index.html.erb:3
    Request
    Parameters:

    None
    Toggle session dump
    Toggle env dump
    Response
    Headers:

    None
    8 条回复    2021-10-11 22:08:56 +08:00
    agagega
        1
    agagega  
       2021-10-10 19:53:37 +08:00 via iPhone
    检查这两个字段是否为空
    0c0c0f
        2
    0c0c0f  
    OP
       2021-10-10 20:29:25 +08:00
    @agagega 哪两个字段?表中的记录确定不是空的
    WildCat
        3
    WildCat  
       2021-10-10 20:52:41 +08:00
    用 find_by!: http://marceloalves.com/notes/ruby/2016/02/26/find_by/

    @cves 是 nil,看行号。
    wangkun025
        4
    wangkun025  
       2021-10-10 21:02:27 +08:00
    已有的代码看,没啥问题。
    0c0c0f
        5
    0c0c0f  
    OP
       2021-10-10 21:08:58 +08:00
    0c0c0f
        6
    0c0c0f  
    OP
       2021-10-10 21:09:22 +08:00
    @WildCatno

    implicit conversion of nil into String
    Extracted source (around line #7):

    def show
    @cve = Cve.find_by!(cve_id: params[:cve_id])
    end
    end

    Rails.root: /Users/admin/RubyProjects/xx-api

    Application Trace | Framework Trace | Full Trace
    app/controllers/cve_controller.rb:7:in `show'
    wangkun025
        7
    wangkun025  
       2021-10-10 23:07:02 +08:00
    楼主的写法不大符合 rails 的要求。
    比如到底是单数和复数的。
    如果 cve 可以是复数的,就直接用复数的。

    还有 find_by 这个,其实一般是用 find(params[:id])的。
    不使用 find_by,也不使用 params[:cve_id]

    还有 cve.cve_id 的话,一般也是 cve.id

    以上都是 rails 的 [约定优于配置] 的体现。
    0c0c0f
        8
    0c0c0f  
    OP
       2021-10-11 22:08:56 +08:00
    class Cve < ApplicationRecord
    connects_to database: { writing: :xxx, reading: :xxx }
    end

    这么配置就没问题

    注意:如果数据库的 schema 不是 public 就需要在 database.yml 中配置 schema_search_path 中指定
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5229 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 09:14 · PVG 17:14 · LAX 02:14 · JFK 05:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.