Aldrin Dela Cruz
Aldrin Dela Cruz

Reputation: 205

before_validation fails in rails

I'm using Rails 3.2.11, Mac OS X Mountain Lion, Ruby 1.9.3

So I have this piece of code:

class Points < ActiveRecord::Base
validates :id, :presence => true

before_create :validate_points

def validate_points
  if self.amount < 0
    Rails.logger.error "Invalid amount of points"
  else
    save!
  end
end

end

I want to restrict users from inserting negative values. But for some reason the validate_points method doesn't work. Anything I'm doing wrong? thanks.

Upvotes: 1

Views: 913

Answers (2)

jvnill
jvnill

Reputation: 29599

You should use the validates_numericality_of method provided by Rails

validates :amount, numericality: { greater_than_or_equal_to: 0 }

UPDATE: issues on your code

There are a couple of issues on your code.

  1. You are using before_create which is called right before the record is saved to the database. The only way to prevent a db commit in this way is to return false in the callback but this is not good practice.
  2. validate_points calls save! but is called in a before_create callback so you're saving your record 2x UPDATE: as pointed out by rxing, this will cause an infinite loop instead of just 2 saves to the database

if you don't want to use the built in validation, try the following

validate :validates_amount_points

def validates_amount_points
  errors.add_to :amount, 'must be greater than or equal to 0' if amount < 0
end

Upvotes: 3

rxing
rxing

Reputation: 373

You need to use 'validation' instead of the before_create hook. BTW, your before_create is not correct either. It would raise SystemStackError: stack level too deep since "save!" will tigger before_create recursively.

Upvotes: 2

Related Questions