我是 ruby on rails 的新手,我继承了一个代码库。现在我无法在我的应用程序中创建新的用户帐户,当我尝试时出现以下错误:
用户中的 NoMethodError::RegistrationsController#create
nil:NilClass 的未定义方法“名称” Rails.root:/home/nathan/dev/legwork-core
应用程序跟踪 |框架跟踪 |全迹
应用程序/模型/contact.rb:74:in block (2 levels) in <class:Contact>'
app/models/user.rb:31:in
更新联系人'
调用代码在这里:
searchable do
string :category do
self.category.name
end
end
Category 应该是 ContactCategory 的一个实例,我想我需要的是将 self.category 设置为默认值(如果它为 nil)。我试过这个来修复它:
after_initialize :set_defaults
def set_defaults
self.category = ContactCategory.first if self.category.nil?
end
我也试过:
def after_initialize
self.category = ContactCategory.first if self.category.nil?
end
我试过:
before_create :set_defaults
def set_defaults
self.category = ContactCategory.first if self.category.nil?
end
有人建议将这个逻辑放在 before_save 中,但是已经有一个 before_save 里面有这个逻辑,这就是我看到作者首先打算成为默认值的地方。
更新:
现在我明白问题出在哪里了,这个问题很愚蠢。我假设赋值语句从未运行过,因为我假设 ContactCategory.first 也不为零。可悲的是,这里的一切都按预期工作。这个故事的寓意是:
我用来设置默认值的所有 Hook 都正常工作。我建议使用它们来使用 ActiveRecord 设置默认值。
最佳答案
我倾向于使用 before_create
回调来设置默认值等等,但是 here's the full list of ActiveRecord callbacks from the RoR API docs .你会注意到 after_initialize
并不像它的名字所暗示的那样工作:
Lastly an
after_find
andafter_initialize
callback is triggered for each object that is found and instantiated by a finder, withafter_initialize
being triggered after new objects are instantiated as well.
您可能想改用 before_save
或 before_create
。
关于ruby-on-rails - 在 Ruby on Rails 中,如何为 ActiveRecord 对象的 member_of 成员分配默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8650618/