ruby-on-rails - 在 Ruby on Rails 中,如何为 ActiveRecord 对象的 member_of 成员分配默认值?

标签 ruby-on-rails ruby activerecord

我是 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 and after_initialize callback is triggered for each object that is found and instantiated by a finder, with after_initialize being triggered after new objects are instantiated as well.

您可能想改用 before_savebefore_create

关于ruby-on-rails - 在 Ruby on Rails 中,如何为 ActiveRecord 对象的 member_of 成员分配默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8650618/

相关文章:

ruby-on-rails - GitHub CI 工作流程上的 Poppler gem 面临错误

ruby-on-rails - 无论支架宽度如何,都强制我的 div 扩展

arrays - 有效删除 Ruby 数组中其他元素的所有子字符串

ruby - 数组上的#concat 和 += 有什么区别?

ruby-on-rails - Rails - 未定义方法 `username' for nil :NilClass

ruby-on-rails - 任何人都可以推荐一个好的但简单的开源 Rails 项目,其中有很多待定的功能可以贡献吗?

ruby - 与 Haskell 的 scanl 对应的 Ruby 是什么?

ruby-on-rails-3 - ActiveRecord::Base#create - 类型错误:无法将符号转换为整数

ruby-on-rails - 如何在删除方法Rails中调用某个路径

ruby-on-rails - 为什么 devise 不通过 gmail smtp 发送电子邮件?