ruby-on-railscallbackbefore-save

Rails 5 - how to negate a method call on a before_save callback conditional


In my Template model I have this callback:

  before_save :set_status, if: :is_template?

  private

  def is_template?
    return self.template_type == 'template'
  end

How can I change it so that it only fires when the template_type is NOT 'template'?

I tried these:

1 before_save :set_status, if: !:is_template?
2 before_save :set_status, if: !(:is_template?)

but they both cause 'method before_save not found' error.

Having read this question, I also tried this:

  before_save :set_status, if: Proc.new {|model| !model.is_template? }

But that seems overkill for such a simple case.

Do I really have to write another method :is_not_template? for this to work?


Solution

  • Try before_save :set_status, unless: :is_template? ;)