Akira  Noguchi
Akira Noguchi

Reputation: 901

allow_blank option is meaningful?

I'm trying to build own app in RoR.
How do you think below code.

class Book < ApplicationRecord
  validates :price,
    presence: true,
    inclusion: { in: 50..100, allow_blank: true }
end

price value must be in 50 to 100 and not empty.
My reviewer want to display "Price is not included in the list" and "Price can't be blank". But I don't agree with this comment.

My prefer code is below. This meets both inclusion and presence.

class Book < ApplicationRecord
  validates :price,
    inclusion: { in: 50..100 }
end

In this case, allow_blank is not meaningful.

How do you think? Which is more prefer?

UPDATE

Using numericality: is better for validating integer.

class Book < ApplicationRecord
  validates :price,
    numericality: { greater_than_or_equal_to: 50, less_than_or_equal_to: 100 }
end

Upvotes: 2

Views: 122

Answers (1)

matthewd
matthewd

Reputation: 4420

Either option is valid; you're trading succinctness of code against precision of the error message shown to the user. Which one works better can depend on the level of user who will be manipulating this record.

For a numeric value, however, consider a numericality: validation instead. "included in the list" is rather confusing phrasing even when a proper [but out of range] number is supplied.

(As an extra idea, consider submitting a PR to Rails to improve both of these default messages.)

Upvotes: 3

Related Questions