Created
January 26, 2015 14:44
-
-
Save maier-stefan/7de17cd85655b9e6351c to your computer and use it in GitHub Desktop.
User auth key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ rails c | |
Loading development environment (Rails 4.1.6) | |
2.1.4 :001 > User.create(email: "[email protected]", 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" = '[email protected]' LIMIT 1 | |
(0.1ms) rollback transaction | |
=> #<User id: nil, email: "[email protected]", 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 > |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.