[英]undefined method `+' for nil:NilClass in Rails
In my user.rb
file under models
, I defined a method full-name
, and called this method in my views. 在
models
下的user.rb
文件中,我定义了一个full-name
方法,并在视图中调用了该方法。 It raises this error that I do not know how to solve. 它引发了一个我不知道如何解决的错误。
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: 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>
Your first_name
attribute contains nil
. 您的
first_name
属性包含nil
。
Since NilClass
does not implement +
method, it raises an error. 由于
NilClass
不实现+
方法,因此会引发错误。 One way to handle that would be to cast values to string: 一种解决方法是将值转换为字符串:
first_name.to_s + " " + last_name.to_s
But the better, idiomatic way is to use string interpolation: 但是更好的惯用方式是使用字符串插值:
def full_name
"#{first_name} #{last_name}"
end
To see the actual value that is contained in a variable you could use 要查看包含在变量中的实际值,可以使用
puts first_name
But, since the nil
value would become an empty string when printed, it would look the same as ""
, a blank string. 但是,由于
nil
值在打印时将变为空字符串,因此它看起来与空白字符串""
相同。 To see if the value is actually nil
when printing, you can use 要查看打印时该值是否实际上为
nil
,可以使用
puts first_name.nil?
# => true
or 要么
puts first_name.class
# => NilClass
Your code is right, just you have one (or more) record with empty value in first_name (and/or empty last_name). 您的代码是正确的,只是您有一个(或多个)记录的first_name(和/或空的last_name)中有空值。 As Nic explained Ruby does not have automatic cast from nil to string, but I suppouse you want to some value for those fields, so I suggest you to use a proper validation for them:
就像Nic解释的那样,Ruby没有从nil到string的自动转换,但是我建议您为这些字段提供一些值,所以我建议您对它们使用适当的验证:
class User < ActiveRecord::Base
validates :first_name, :last_name, presence: true
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.