Reputation: 11
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
Upvotes: 1
Views: 297
Reputation: 76784
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"
Upvotes: 0
Reputation: 541
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.
Upvotes: 1