Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validation - maximum database entries

I have a rails project, using active record and was wondering if there was a validation helper for max number of individual entries. For example, if you had a form submission and only wanted, say 2, and you just wanted the first 2 to be persisted to the table, how would you do this?

I have read the manual and had a look at numericality etc but it's not really what I'm looking for. I have tried to write my own validation method in the model, but I am assuming there is a validation helper that makes this easier:

  def validatePassengerNumber 
    if self.passengers.length > 2
      # unsure on how to refuse new data access to database
    end
  end
like image 491
user3927582 Avatar asked Dec 10 '25 19:12

user3927582


2 Answers

Add an error to base after check return true, and it will prohibit to save into database.

 def validate_passenger_number        
     self.errors.add(:base, "exceed maximum entry") if self.passengers.length > 2
 end 

Call this custom validation in respective model.

  validate :validate_passenger_number, on: :create
like image 83
Rokibul Hasan Avatar answered Dec 13 '25 07:12

Rokibul Hasan


There's no built-in validation; at least I haven't come across any. But following is a way to impose this type of validation:

  def max_passengers
    if self.passengers.count > 2
      errors.add_to_base("There should not be more than 2 passengers.")
    end
  end

And then, you can use this validation to impose a check on the number of passengers.

like image 39
Arslan Ali Avatar answered Dec 13 '25 07:12

Arslan Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!