Edgars
Edgars

Reputation: 953

Add unique identifer to model on create, Rails 4

I am forced to avoid default id for some actions.

I have model Advertisement.I added new column called identifier. Now I want to add unique random integer sequence when I create new advertisement.

So far I came up with this solution :

class Advertisement < ActiveRecord::Base

   before_create :add_identifier

      def add_identifier      
        identifier = ('0'..'9').to_a.shuffle.first(5).join    
      end
end

This far it just creates random 5 digits long number. But how can check if any advertisements created before have this number already ? And how to insert it in databese while created ?

Or better solution would be in controller under Create action ?

Thanks

Upvotes: 0

Views: 31

Answers (1)

sjaime
sjaime

Reputation: 1500

This piece of code will retry up to 5 times to generate a id that's not already taken. You'll probably want to add a uniqueness validation (and a unique index constraint in the DB) for your identifier attribute. Also, take a look at the SecureRandom ruby module for generating random identifiers.

class Advertisement < ActiveRecord::Base

  before_create :add_identifier

  def add_identifier
    retries = 0
    loop do
      self.identifier = ('0'..'9').to_a.shuffle.first(5).join
      retries += 1
      break if retries == 5 || !self.class.find_by(identifier: self.identifier)
    end
  end

end

Upvotes: 1

Related Questions