Anonymous user at devise - rails

I am new to rails and I tried to do a simple authentication with an anonymous user. I followed this tutorial and I have this error:

undefined method `find_or_initialize_by_token'

      

This is my AnonymousUser model:

class AnonymousUser < User
  ACCESSIBLE_ATTRS = [:name, :email]
  attr_accessible *ACCESSIBLE_ATTRS, :type, :token, as: :registrant
  def register(params)
    params = params.merge(type: 'User', token: nil)
    self.update_attributes(params, as: :registrant)
  end
end

      

This is my user model:

class User < ActiveRecord::Base
  devise :database_authenticatable, :confirmable, :lockable, :recoverable,
    :rememberable, :registerable, :trackable, :timeoutable, :validatable,
    :token_authenticatable
  attr_accessible :email, :password, :password_confirmation, :remember_me
end

      

And the last important one is my ApplicationController which has this error:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def authenticate_user!(*args)
    current_user.present? || super(*args)
  end

  def current_user
    super || AnonymousUser.find_or_initialize_by_token(anonymous_user_token).tap do |user|
      user.save(validate: false) if user.new_record?
    end
  end

  private
  def anonymous_user_token
    session[:user_token] ||= SecureRandom.hex(8)
  end
end

      

Someone told me that if the user AnonymousUser inherits the user, then AnonymousUser has a method called find_or_initialize_by_token

, but I don't know how to fix it.

+3


source to share


2 answers


If you have the latest rails installed, try refactoring:

# in ApplicationController#current_user

AnonymousUser.find_or_initialize_by_token(anonymous_user_token).tap do |user|
  user.save(validate: false) if user.new_record?
end

      

like that:



AnonymousUser.safely_find(anonymous_user_token)

      

and click find_or_initialize_by_token

and save(validate: false)

into the model.

+1


source


I wrote the blog post you linked to, but today I would use

AnonymousUser.where(anonymous_user_token: anonymous_user_token).first_or_initialize

      



Dynamic searchers are deprecated AFAIK.

However, @Saurabh Jain is absolutely correct in his assumption to refactor this block into a cool little button-type method on AnonymousUser.

+1


source







All Articles