I have Users Bands and Codes.
A user creates a code and that code has a user_id and a band_id.
I have a before save callback generating the code.
before_create :generate_code
private
def generate_code
self.code = SecureRandom.hex(3)
end
I need to add a check, if code exists with user_id and band_id, return false
That way a user will only have one code per band
thoughts?
if you want to keep generating until you get a valid code, try:
if you just want to try one code, and return false, try:
Note: change “User” to whatever your relation you’re checking the collision in 🙂
Alternatively, you could just try
validates :code, :uniqueness => trueor something similar 🙂