简体   繁体   中英

Ruby on Rails: validation two inclusion conditions with range

We have validation on a model to validate "year built".

  validates :year_built, inclusion: { in: 1900..(Date.today.year) }

This column was recently changed to a string to allow for two more options "To Be Built" and "New".

I would like to validate that the only accepted data will be what is above (1900..date) as well as these two strings:

validates :year_built, inclusion: { in: 1900..(Date.today.year) || ['New', 'To Be Built']}

Is there a way I can check for both?

See here for validations in Rails .

The inclusion validator is a basic validator for ranges OR arrays, but doesn't allow for this type of "conditional" logic.

While I doubt that changing a year column to string was the best choice in the first place ( you can also conditionally validate based on another column ), you could adapt your idea and map / collect the years you want to match against and add the other options to that array, eg:

validates :year_built, inclusion: { in: (1900..(Date.today.year)).collect(&:to_s) + ['New', 'To Be Built']}

But I think this options puts too much in a single hard to parse line. If you want to keep your column a String-column you should consider writing a custom validator function, see here for how to write one .

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