简体   繁体   中英

Rails - Validate unique month in year

Using Rails 6.

I have a model, MonthlyConsumption , which is a measure of a monthly energy consumption. It contains the following fields:

  • month as an integer from 1-12; This is later converted into a month using some key-value pairs eg 1: 'January'
  • year : an integer, eg 2020
  • amount : an integer, the amount of power consumption in kW
  • city_id : A reference to a City model

I want to validate that there is only 1 possible entry in one month of a given year, per city.

For example:

  • 500kW in January 2020 in City X & 600kW in January 2021 in City X should both be valid
  • 500kW in January 2020 in City X & 600kW in January 2020 in City Y should both be valid
  • 500kW in January 2020 in City X & 600kW in January 2020 in City X should be invalid

What would be the best way of accomplishing this validation?

就像是:

validates :month, uniqueness: { scope: [:city_id, :year] }

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