预期相同的拼写会导致错误.为什么?

the*_*ass 5 ruby ruby-on-rails ruby-on-rails-4 ruby-2.1

我正在读这个问题,它说的是电话

something {|i| i.foo }
something(&:foo)
Run Code Online (Sandbox Code Playgroud)

是等价的.

现在我试图重构我的模型AdminUser根据这个模式命名并替换

after_create { |admin| admin.send_reset_password_instructions }
Run Code Online (Sandbox Code Playgroud)

after_create(&:send_reset_password_instructions)
Run Code Online (Sandbox Code Playgroud)

,但是当我正在运行包含行的迁移时

def migrate(direction)
  super
  # Create a default user
  AdminUser.create!(email: 'a@b.de', password: 'very_clever', password_confirmation: 'very_clever') if direction == :up
end
Run Code Online (Sandbox Code Playgroud)

它给了我错误

ArgumentError: no receiver given
Run Code Online (Sandbox Code Playgroud)

指着这条线AdminUser.create!....

谁能告诉我这里出了什么问题?

Tim*_*ins 0

我知道这是一个较老的问题,但它让我很感兴趣,促使我自己做了一些研究。我没有为您提供更正的代码答案,但环顾四周,我相信这篇文章将方法传递给迭代器方法时发生的情况非常密切相关,并且很可能会回答您的“这里出了什么问题?”的问题。

基本上,因为您现在正在向它传递一个带有重构代码的过程,所以它需要一个特定的参数,表明您AdminUser不再传递它并导致它没有接收器的错误。

话虽这么说,我确信您有按照自己的方式设置代码的理由,但基于您正在做的事情的隐含想法和上下文,我同意@photoionized 使用, after_create :send_reset_password_instructions因为它清晰、简洁并且(很可能)有您想要的结果。