Skip to content

Instantly share code, notes, and snippets.

@maier-stefan
Created January 26, 2015 14:44
Show Gist options
  • Save maier-stefan/7de17cd85655b9e6351c to your computer and use it in GitHub Desktop.
Save maier-stefan/7de17cd85655b9e6351c to your computer and use it in GitHub Desktop.
User auth key
$ rails c
Loading development environment (Rails 4.1.6)
2.1.4 :001 > User.create(email: "stefan@gmail.com", password: "somepassword123", password_confirmation: "somepassword123")
(0.2ms) begin transaction
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."auth_token" = '' LIMIT 1
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'stefan@gmail.com' LIMIT 1
(0.1ms) rollback transaction
=> #<User id: nil, email: "stefan@gmail.com", encrypted_password: "$2a$10$l6LMCC4/LbAZQUxQBZK04O9ks3WXswUNfzhAQpMwBGe...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil, auth_token: "">
2.1.4 :002 >
class User < ActiveRecord::Base
validates :auth_token, uniqueness: true
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
before_create :generate_authentication_token!
has_many :products, dependent: :destroy
def generate_authentication_token!
begin
self.auth_token = Devise.friendly_token
end while self.class.exists?(auth_token: auth_token)
end
end
@maier-stefan
Copy link
Author

Problem was the validation because i have already created a User before adding the auth_token, so a empty auth token was already in the db. Of course that the before_create method is called before save the User is set up with the default value "" => the rollback is made before the before_create method is called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment