【问题标题】:A spelling, expected to be equivalent, causes error. Why?预期是等价的拼写会导致错误。为什么?
【发布时间】:2016-09-10 01:00:21
【问题描述】:

我正在阅读this question,上面写着电话

something {|i| i.foo }
something(&:foo)

是等价的。

现在我正在尝试根据此模式重构名为 AdminUser 的模型并替换

after_create { |admin| admin.send_reset_password_instructions }

after_create(&:send_reset_password_instructions)

,但是当我运行我的迁移时,其中包含行

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

它给了我错误

ArgumentError: no receiver given

指向AdminUser.create!...这一行。

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

【问题讨论】:

  • 我看不出你不能用更短的形式替换after_create { |admin| admin.send_reset_password_instructions },所以我会在别处寻找问题。你在想,“但在我做出改变之前它就起作用了”,但我会仔细检查你是否做了其他改变,也许是无意的。
  • 更好,为什么不直接做after_create :send_reset_password_instructions

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-2.1


【解决方案1】:

我知道这是一个较老的问题,但它对我很感兴趣,因此我自己进行了一些研究。我没有更正的代码答案,但环顾四周,我相信这篇文章 what happened when pass a method to iterator method 非常相关,很可能会回答你的问题“这里出了什么问题?”

基本上,因为您现在正在向它传递一个带有重构代码的 proc,所以它期望您的 AdminUser 不再传递它并导致它没有接收器的错误。

话虽如此,我相信你有你的理由来设置你的代码,但基于你在做什么的隐含想法和上下文,我同意@photoionized 使用 after_create :send_reset_password_instructions,因为它清晰、简洁并且(很可能)有您想要的结果。

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2021-12-19
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2020-07-16
    • 2014-06-05
    相关资源
    最近更新 更多