In my Rails app I have classes that depend on one another, ParkingSpace and Parking Lot.
A ParkingLot has many ParkingSpaces and the ParkingSpace belongs to a ParkingLot.
I want to ensure that the same ParkingSpace can’t be inserted into the ParkingLot again.
Typically, I would use a uniqueness validation to ensure that the ParkingSpace can’t be repeated parking space have very generic names
ParkingLot with id:1 can have ParkingSpaces 1, 2 and 3 on it.
ParkingLot with id:2 can also have ParkingSpaces 1, 2 and 3 on it.
But the above parking lots should not be able to have two parking spaces with the same name.
How can I validate this in Rails?
How can I validate this at the database level?
I’m considering joining the two fields together in a unique way and then calling unique on that. Is this a valid approach? (Not exactly sure how to do this at the database level, but all my validations need to be present there.)
(using Postgres)
Assuming your parking space and an identifier (like a name), you would do something in the ParkingSpace class like: