Tony Vincent
Tony Vincent

Reputation: 14282

before_validation on create not working

In my model I have

class Test < ActiveRecord::Base
  before_validation :set_pending, on: :create
  validates :status, presence: true, inclusion: { in: %w(passed failed pending) }
  .
  .
  .
  private

  def set_pending
    status = 'pending'
  end
end

In my rails console I am trying to create a new Test

Test.create!(user_id: 9, runnable: true) 

But I am getting error

ActiveRecord::RecordInvalid: Validation failed: Status can't be blank

What am I doing wrong? I am on ruby 2.1.8 and rails 4.0.13. Thanks

Upvotes: 3

Views: 1639

Answers (1)

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

My personal preference is to be very explicit when setting variables, and indeed you are missing a self

def set_pending self.status = 'pending' end

Upvotes: 9

Related Questions