Ruby on rails Rails 6-NoMethodError(未定义的方法`titleize';用于nil:NilClass)

Ruby on rails Rails 6-NoMethodError(未定义的方法`titleize';用于nil:NilClass),ruby-on-rails,nomethoderror,ruby-on-rails-6,Ruby On Rails,Nomethoderror,Ruby On Rails 6,我在这里查看了有关我的错误的问题,但它们似乎无关,因此这篇文章。 在我的UserProfile模型中有一个“capitalize_names”方法,当我在控制台中更新属性时会抛出这个错误。但是模型得到了更新,即使我得到了这个错误。我尝试将我的实例方法设置为私有的、受保护的。但结果是一样的。不知道我错过了什么。 非常感谢你的帮助 我的模型: class UserProfile < ApplicationRecord belongs_to :user before_update :ca

我在这里查看了有关我的错误的问题,但它们似乎无关,因此这篇文章。 在我的UserProfile模型中有一个“capitalize_names”方法,当我在控制台中更新属性时会抛出这个错误。但是模型得到了更新,即使我得到了这个错误。我尝试将我的实例方法设置为私有的、受保护的。但结果是一样的。不知道我错过了什么。 非常感谢你的帮助

我的模型:

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
class UserProfile
这是我的控制台:

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)
irb(主):004:0>u
=> #
irb(主要):005:0>u.profile
=> #
irb(main):006:0>u.profile.update(名字:“somecool name”)
回溯(最近一次呼叫最后一次):
2:来自(irb):6
1:来自app/models/user_profile.rb:16:在“大写名称”中
NoMethodError(nil:NilClass的未定义方法'titleize')
但是,正如你所看到的,我的模型仍然得到了成功的更新

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">
irb(main):007:0>u.profile
=> #

问题是您第二次调用
标题
,因为在示例中
self.last\u name
nil
。您不能在nil上调用titleize,但您的记录仍会被修改,因为对titleize的第一次调用是针对
self.first\u name
,它是一个字符串。为了避免异常,可以将两个字段的默认值设置为空字符串,或者检查它们是否为零

def大写\u名称
self.first\u name=self.first\u name.try(:titleize)
self.last\u name=self.last\u name.titleize,除非self.last\u name.nil?
结束

太棒了!我用空字符串为名字和姓氏重新生成了我的模式,它成功了!我不知道。非常感谢你@R.塞拉