undefined局部变量或方法after_create回调

时间:2017-12-14 16:41:25

标签: ruby-on-rails activerecord callback

在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'对于   //用户:0x007ffcae55c618 //你的意思是? is_sibling?

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

4 个答案:

答案 0 :(得分:0)

if中有一点错字。正确的方法是:

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

答案 1 :(得分:0)

将代码更改为:

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

答案 2 :(得分:0)

我更改了is_sibling?方法签名并删除了问号,现在它的is_sibling就像这样:

after_create :enroll_in_plan, :match_to_sibling, if: :is_sibling

但为什么?

答案 3 :(得分:0)

您可以将其与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