Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

How to deal with guest users? #24

Closed
seivan opened this issue Dec 30, 2009 · 2 comments
Closed

How to deal with guest users? #24

seivan opened this issue Dec 30, 2009 · 2 comments

Comments

@seivan
Copy link

seivan commented Dec 30, 2009

I got

def initialize(user)
 user ||= login_as_trial_user
 
  private
  def login_as_trial_user
    name = "anonymous_#{Time.now.to_i + rand}"
    if User.find_by_username(name)
      UserSession.create(User.find_by_username(name),true)
    else
      guest_role = User.create(:username => name, :password => name, :password_confirmation => name, :role => "guest", :email => "change@this.com")
      UserSession.create(guest_role, true)
    end
    @current_user_session = UserSession.find
    guest_role
  end

This is in the Ability.rb
Is that the correct way to go? Or should one use a before_filter in application_controller.rb so current_user is always set?
The problem is that SOMETIMES you don't need the current_user, and therefore it's uncessary to do a query for every request.

This way it only do it when the ability gets called.
:-) But I am trying to figure out wether this is the right approach?

@ryanb
Copy link
Owner

ryanb commented Dec 31, 2009

Does the guest user serve any other purpose outside of the Ability class? If not you can just define an instance of User in memory instead of creating one to the database each time.

def initialize(user)
  user ||= User.new(...)
end

However, if the guest user does need to be saved to the database and stored in the session then it should happen outside of the Ability class. This is because Ability knows nothing of the current request/session.

I recommend doing this in the current_user method. Something like.

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
  @current_user ||= User.create!(....) # make guest user
  @current_user
end

This way the guest user will only be created upon fetching the current user. Does this work for you?

@ryanb
Copy link
Owner

ryanb commented Feb 2, 2010

Closing because I haven't heard back and I am assuming this resolved the problem.

This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants