【问题标题】:undefined local variable or method after_create callback未定义的局部变量或方法 after_create 回调
【发布时间】:2017-12-14 16:41:24
【问题描述】:

在 activerecord 模型中执行 after_create 回调时出现此错误。

首先,我有 2 个 after_create 回调,一个应该为所有人运行,另一个应该只在用户是兄弟姐妹时运行:

  # callbacks
  after_create :couple_with_role 
  after_create :enroll_in_plan, :match_to_sibling, if: :is_sibling?

  def is_sibling?
    roles.include?('sibling')
  end

错误如下:

NameError: 未定义的局部变量或方法 `is_sibling' for //用户:0x007ffcae55c618// 你的意思是? is_sibling?

这样做的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord callback


    【解决方案1】:

    您的if 中有一个小错字。正确的做法是:

    after_create :enroll_in_plan, :match_to_sibling, if: -> { is_sibling? }
    

    【讨论】:

    • @duxfox——好的。我已经编辑了我的答案,你可以试试吗?
    • 我刚试了一下,还是一样的错误...这真是奇怪
    • 当我将方法签名更改为 is_sibling 时没有问号
    【解决方案2】:

    把代码改成:

    after_create :couple_with_role 
    after_create :enroll_in_plan, :match_to_sibling, if: Proc.new { |user| user.roles.include?('sibling') }
    

    Read Using :if and :unless with a Symbol

    Using :if and :unless with a Proc

    【讨论】:

      【解决方案3】:

      我更改了is_sibling? 方法签名并删除了问号,所以现在它的is_sibling 是这样工作的:

      after_create :enroll_in_plan, :match_to_sibling, if: :is_sibling
      

      但是为什么?

      【讨论】:

        【解决方案4】:

        您可以将它与 proc 一起使用,请参阅here

        after_create :normalize_card_number, if: :paid_with_card?
        

        或者您可以将 Proc 传递给 if 子句

          after_create :enroll_in_plan, if: :is_sibling?
        
          def enroll_in_plan
          end
          def is_sibling?
          end
        

        这也适用于 rails 4

        【讨论】:

        • 这正是我所拥有的,但它不适用于“?”在方法名中
        • 如本问题stackoverflow.com/questions/7314493/… 中所引用的,如果您将主体操作为内联proc,它是否与proc 一起工作?
        猜你喜欢
        • 2017-01-26
        • 2018-04-19
        • 2015-01-01
        • 2013-12-17
        • 2016-04-29
        • 2018-04-21
        相关资源
        最近更新 更多