gpt4 book ai didi

ruby-on-rails - 未定义方法 `+' 为 nil :NilClass in Rails

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:51 24 4
gpt4 key购买 nike

在我的 models 下的 user.rb 文件中,我定义了一个方法 full-name,并在我的 View 中调用了这个方法。它引发了这个我不知道如何解决的错误。

NoMethodError in Statuses#index
Showing app/views/layouts/application.html.erb where line #24 raised:
undefined method `+' for nil:NilClass
Extracted source (around line #10):

def full_name
first_name + " " + last_name
end

Rails.root:

Application Trace | Framework Trace | Full Trace
app/models/user.rb:10:in `full_name'
app/views/layouts/application.html.erb:24:in `_app_views_layouts_application_html_erb__1801360389632919652_70105866374460'
<li>
<%= link_to current_user.full_name, edit_user_registration_path %>
</li>

最佳答案

您的 first_name 属性包含 nil

由于 NilClass 没有实现 + 方法,它会引发错误。一种处理方法是将值转换为字符串:

first_name.to_s + " " + last_name.to_s

但更好的惯用方法是使用字符串插值:

def full_name
"#{first_name} #{last_name}"
end

要查看包含在变量中的实际值,您可以使用

puts first_name

但是,由于 nil 值在打印时会变为空字符串,因此它看起来与 "" 一样,都是空字符串。要在打印时查看该值是否实际上是 nil,您可以使用

puts first_name.nil?
# => true

puts first_name.class
# => NilClass

关于ruby-on-rails - 未定义方法 `+' 为 nil :NilClass in Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38105529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com