[英]Rails 6 - NoMethodError (undefined method `titleize' for nil:NilClass)
I looked through questions here about my error, but they are seems unrelated, hence this post. 我在这里浏览了有关我的错误的问题,但它们似乎无关,因此本文发布了。 I have a 'capitalize_names' method in my UserProfile model that throw this error when I update attributes in the console.
我的UserProfile模型中有一个'capitalize_names'方法,当我在控制台中更新属性时会抛出此错误。 But the model gets updated even though I get this error.
但是,即使出现此错误,模型也会更新。 I tried making my instance method private, protected.
我尝试将实例方法设为私有,受保护。 But the results is the same.
但是结果是一样的。 Not sure what I'm missing here.
不知道我在这里想念的是什么。 Big thank you in advance for your help.
非常感谢您的帮助。
My model: 我的模特:
class UserProfile < ApplicationRecord
belongs_to :user
before_update :capitalize_names
# i tried protected or private still gets the same result!!
def capitalize_names
self.first_name = self.first_name.titleize
self.last_name = self.last_name.titleize
end
end
Here's my console out put: 这是我的控制台输出:
irb(main):004:0> u
=> #<User id: 25, username: "somename1", email: "bhati12345@gmail.com", created_at: "2019-09-14 14:09:46", updated_at: "2019-09-14 14:09:46">
irb(main):005:0> u.profile
=> #<UserProfile id: 25, first_name: nil, last_name: nil, user_id: 25, pop_value: nil, time_zone: nil, country: nil, sketch_profile: {}, profile_image: nil, logo: nil, created_at: "2019-09-14 14:09:46", updated_at: "2019-09-14 14:09:46", gender: "male">
irb(main):006:0> u.profile.update(first_name: 'somecool name')
Traceback (most recent call last):
2: from (irb):6
1: from app/models/user_profile.rb:16:in `capitalize_names'
NoMethodError (undefined method `titleize' for nil:NilClass)
But, as you can see my model still got successfully updated... 但是,正如您所看到的,我的模型仍然可以成功更新...
irb(main):007:0> u.profile
=> #<UserProfile id: 25, first_name: "Somecool Name", last_name: nil, user_id: 25, pop_value: nil, time_zone: nil, country: nil, sketch_profile: {}, profile_image: nil, logo: nil, created_at: "2019-09-14 14:09:46", updated_at: "2019-09-14 14:10:52", gender: "male">
The problem is your second call to titleize
, because in the example self.last_name
is nil
. 问题是您第二次调用
titleize
,因为在示例中self.last_name
为nil
。 You cannot call titleize on nil, but your record still gets modified because the first call to titleize is for self.first_name
which is a string. 您不能在nil上调用titleize,但是您的记录仍然会被修改,因为第一次调用titleize是针对
self.first_name
,这是一个字符串。 To avoid the exception you could set the default value of both fields to an empty string, or check they aren't nil 为了避免出现异常,您可以将两个字段的默认值都设置为空字符串,或者检查它们是否为nil
def capitalize_names
self.first_name = self.first_name.try(:titleize)
self.last_name = self.last_name.titleize unless self.last_name.nil?
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.