Search code examples
ruby-on-railsrubymethodsbefore-save

before_save if attribute.present?


before_save :date_started_sets_deadline, if date_started.present?

I don't want this before_save to run if :date_started == nil. I've tried various versions of the above line so not sure if I have to change that or the method itself.

def date_started_sets_deadline
  if self.date_started > Date.tomorrow
    self.deadline = self.date_started
  end
end

I'm trying to avoid the error NoMethodError (undefined method '>' for nil:NilClass): app/models/challenge.rb:35:in 'date_started_sets_deadline' whenever a user tries to create a challenge without a date_started


Solution

  • Change the before_save statement to the following:

    before_save :date_started_sets_deadline, if: :date_started?

    If you provide a symbol to the if, then rails evaluates it in the context of the instance. By adding ?, it is a auto generated method which is essentially same as date_started.present?.

    Also, if the date_started is required within the date_started_sets_deadline implementation, I would also add the check explicitly instead of solely depending on adding the if condition on the callback logic.

    def date_started_sets_deadline
      if self.date_started.present? && (self.date_started > Date.tomorrow)
        self.deadline = self.date_started
      end
    end
    

    Refer to Using :if and :unless with a Symbol for more info.