0

I'm getting this error when the after_create callback is executed in an activerecord model.

first of all, I have 2 after_create callbacks, one should run for everyone, and the other should only run if the user is a sibling:

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

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

and the error looks like this:

NameError: undefined local variable or method `is_sibling' for //User:0x007ffcae55c618// Did you mean? is_sibling?

What's the correct way to do this?

Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

4 Answers4

0

There is a little typo in your if. The correct way to do this is :

after_create :enroll_in_plan, :match_to_sibling, if: -> { is_sibling? }
Samy Kacimi
  • 1,216
  • 9
  • 23
0

Change the code as:

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

Shamsul Haque
  • 2,441
  • 2
  • 18
  • 20
0

I changed the is_sibling? method signature and removed the question mark, so now its is_sibling and it works like this:

after_create :enroll_in_plan, :match_to_sibling, if: :is_sibling

but why?

Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127
0

you can use it with proc see here

after_create :normalize_card_number, if: :paid_with_card?

or you can pass a Proc to if clause

  after_create :enroll_in_plan, if: :is_sibling?

  def enroll_in_plan
  end
  def is_sibling?
  end

This also works for rails 4

Rahul Sharma
  • 1,393
  • 10
  • 19
  • that's exactly what I have but its not working with the '?' in the method name – Abdul Ahmad Dec 14 '17 at 17:20
  • as referenced in this question https://stackoverflow.com/questions/7314493/how-should-i-use-after-create-with-a-condition-in-the-model is it working with proc for you if you action body into inline proc? – Rahul Sharma Dec 14 '17 at 17:24