Maxwwos
Maxwwos

Reputation: 49

Rails validations if condition

I need your help validating a simple Rails model.

First i want to check if the user filled all input-fields:

class Test < ActiveRecord::Base

   validates :firstname, :lastname, :firstvalue, :secondvalue, presence: true

   [...]

I also want to check if the :secondvalue param is bigger than :firstvalue.

Adding

validate :biggerThan

def biggerThan

    if self.secondvalue < self.firstvalue

        errors.add(:secondvalue, "must be bigger than First")

    end
end

Well this works, but only if all other fields are filled! Creating a new Entry leaving all fields blank i am getting an undefined method <' for nil:NilClass.

Could you help me?

Upvotes: 1

Views: 165

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can do this

validate :biggerThan, if: Proc.new{ |test| test.firstvalue.present? and test.secondvalue.present? }

It would be good if you add numericality validations also

validates :firstvalue, numericality: true
validates :secondvalue, numericality: true

Upvotes: 2

Related Questions