ruby on rails: no implicit conversion of nil into String

2021-10-10 19:07:02 +08:00
 0c0c0f
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
2106 次点击
所在节点    Ruby on Rails
8 条回复
agagega
2021-10-10 19:53:37 +08:00
检查这两个字段是否为空
0c0c0f
2021-10-10 20:29:25 +08:00
@agagega 哪两个字段?表中的记录确定不是空的
WildCat
2021-10-10 20:52:41 +08:00
用 find_by!: http://marceloalves.com/notes/ruby/2016/02/26/find_by/

@cves 是 nil,看行号。
wangkun025
2021-10-10 21:02:27 +08:00
已有的代码看,没啥问题。
0c0c0f
2021-10-10 21:08:58 +08:00
0c0c0f
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
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
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 中指定

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/806875

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX