简体   繁体   中英

How do you validate numbers with Ruby On Rails using % operator

I want to make sure that numbers coming into this object are divisible by 3. How do I use the validate on the model to prevent invalid input?

Thanks!

Try this:

# your_model.rb
validate :only_valid_numbers

private

    def only_valid_numbers
        if (self.number % 3) != 0
            self.errors[:base] << "Number must be divisible by 3!"
        end
    end

Remember that 0 % 3 will be 0, so if you don't want to allow that, change the if statement to:

if self.number != 0 and ...etc...

You can write your own simple validation method for this like so:

validate :divisible_by_three

def divisible_by_three
  unless attribute%3 == 0
    self.errors.add(:attribute, "is not divisible by 3")
  end
end

I don't think any of the built in rails methods so this is probably the best solution.

Tom

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM