[Ruby / Rails] Set a unique (unique) value in the class

For rubocop, loop + break is recommended.

loop + break version

class Nonce
  def set_nonce
    return true if nonce.present? #Guard to prevent overwriting

    self.nonace = loop do
      random_str = SecureRandom.urlsafe_base64
      break random_str unless self.class.exists?(nonce: random_str)
    end
  end
end

while version

class Nonce
  def set_nonce
    return true if nonce.present? #Guard to prevent overwriting

    begin
      self.nonce = SecureRandom.urlsafe_base64
    end while self.class.exists?(nonce: nonce)
  end
end

before_create or before_validation

If you are writing validates like this, you need to use before_validation because using before_create will get stuck in validation.

class SomeClass
  validates :nonce, presence: true, uniqueness: true

  before_validation :set_nonce

  private

  def set_nonce
    return true if nonce.present?

    self.nonace = loop do
      random_str = SecureRandom.urlsafe_base64
      break random_str unless self.class.exists?(nonce: random_str)
    end
  end
end

Test example

# frozen_string_literal: true

require 'rails_helper'

describe Nonce, type: :model do
  describe '#set_nonce' do
    it do
      nonce = Nonce.create!
      expect(nonce.nonce.size).to eq(8)
    end

    it do
      nonce = Nonce.new
      expect(nonce.nonce).to be_nil
      nonce.save!
      expect(nonce.nonce.size).to eq(8)
    end

    it do
      nonce = Nonce.create!
      nonce_str = nonce.nonce
      nonce.update!(updated_at: Time.current)
      expect(nonce.nonce).to eq(nonce_str)
    end
  end
end

Recommended Posts

[Ruby / Rails] Set a unique (unique) value in the class
Determine that the value is a multiple of 〇 in Ruby
Class in Ruby
Steps to set a favicon in Rails
I tried to make a parent class of a value object in Ruby
[Order method] Set the order of data in Rails
Recommendation of Service class in Ruby on Rails
(Ruby on Rails6) Creating data in a table
I want to get the value in Ruby
How to make a unique combination of data in the rails intermediate table
How to set the display time to Japan time in Rails
[Ruby on Rails Tutorial] Error in the test in Chapter 3
Calculate the difference between numbers in a Ruby array
[Rails 6] How to set a background image in Rails [CSS]
Ruby on Rails Incorrect string value error resolution when posting a form in Japanese
Write class inheritance in Ruby
Multiplication in a Ruby array
Difficulties in building a Ruby on Rails environment (Windows 10) (SQLite3)
[Ruby on Rails] Quickly display the page title in the browser
How to retrieve the hash value in an array in Ruby
A note about the seed function of Ruby on Rails
How to display a graph in Ruby on Rails (LazyHighChart)
Mapping to a class with a value object in How to MyBatis
Apply CSS to a specific View in Ruby on Rails
Sorting hashes in a Ruby array
Add a search function in Rails.
About the symbol <%%> in Rails erb
[Ruby] Relationship between parent class and child class. The relationship between a class and an instance.
Create a new app in Rails
Ruby on Rails Japanese-English support i18n
A memorial service for the library used when competing in Ruby
Implement a gRPC client in Ruby
(Ruby on Rails6) Creating a database and displaying it in a view
A murmur about the utility class
Implement a contact form in Rails
Install Rails in the development environment and create a new application
I summarized the flow until implementing simple_calendar in Ruby on Rails.
Things to remember and concepts in the Ruby on Rails tutorial
I want to change the value of Attribute in Selenium of Ruby
Ruby methods often used in Rails
(Ruby on Rails6) Create a function to edit the posted content
[Caution summary] Set Ruby time (Time type/Date type/DateTime type) in the column
Change from SQLite3 to PostgreSQL in a new Ruby on Rails project
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Ruby] Processing with multiple colons. A class that utilizes the module namespace.
The parameters I received in Rails were a bit different than I expected
"" Application.js "is not present in the asset pipeline" error in Ruby on Rails
Sample program that returns the hash value of a file in Java
How to change the value of a variable at a breakpoint in intelliJ
I thought about the best way to create a ValueObject in Ruby
How to debug the processing in the Ruby on Rails model only on the console
Cloud IDE: Heroku couldn't be installed in the Ruby on Rails tutorial
[Ruby] Returns characters in a pyramid shape according to the entered numbers
[Ruby / Rails] Use alias. In a way that rubocop won't get angry!
A series of flow of table creation → record creation, deletion → table deletion in Ruby on Rails
Get the value of enum saved in DB by Rails with attribute_before_type_cast
Set up a Java GUI in a separate thread to keep the main
[Java] Implement a function that uses a class implemented in the Builder pattern
What is a class in Java language (3 /?)
I tried a calendar problem in Ruby
A review note for the class java.util.Scanner