1

Hi I am trying to generate Token to authenticate rails Api client. I have used generate_key_method in mode class.

class ApiKey < ActiveRecord::Base

before_create :generate_access_token

validates :access_token, uniqueness: true

def generate_access_token
  begin
    self.access_token = SecureRandom.hex
  end while self.class.exists?(access_token: access_token)
 end
end

inserts null while creating record

fool-dev
  • 7,671
  • 9
  • 40
  • 54
Arun Kumar
  • 11
  • 2

2 Answers2

1

before_create callbacks happen after validation. In your case, the uniqueness validation is failing and halting the callback chain before the before_create callbacks can be triggered. You can set the access token before validating on create:

before_validation :generate_access_token, on: :create

Please see the page on active record callbacks for more information and for the whole ordering.

AOG
  • 521
  • 2
  • 8
0

You'll want to look at this answer.

The correct way to achieve what you're doing is to use the following:

#app/models/api_key.rb
class ApiKey < ActiveRecord::Base

  before_create :generate_key

  protected

  def generate_key
    self.access_token = loop do
      random_token = SecureRandom.hex
      break random_token unless ApiKey.exists?(access_token: random_token) #-> this acts in place of the validation
    end
  end

end

--

The above is now deprecated, in favour of ActiveRecord's Secure Token functionality:

#app/models/api_key.rb
class ApiKey < ActiveRecord::Base
   has_secure_token :access_token
end

key = ApiKey.new
key.save 
key.access_token # -> "pX27zsMN2ViQKta1bGfLmVJE"
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147