Allow anonymous/guest user to “try out” functionality without registering in Rails/Devise/CanCan app

前端 未结 2 2076
不知归路
不知归路 2021-02-06 14:08

I\'m developing a Rails 3 app using Devise and CanCan.

The app allows anonymous (not registered) users to access some of the app, and registered users to access other par

2条回答
  •  失恋的感觉
    2021-02-06 14:19

    In Ryan's introduction to CanCan he offers the following suggestion:

    Make a New User object in memory for guest users on the site, but don't save it. This way all of your functions that need to associate to a user will still work, but they won't save.

    See the railscast here: http://railscasts.com/episodes/192-authorization-with-cancan

    Ryan's code example is:

    class Ability  
      include CanCan::Ability  
    
      def initialize(user)  
        user ||= User.new # This initializer is creating your memory-only guest users
    
        if user.role? :admin  
          can :manage, :all  
        else  
          can :read, :all  
          can :create, Comment  
          can :update, Comment do |comment|  
            comment.try(:user) == user || user.role?(:moderator)  
          end  
          if user.role?(:author)  
            can :create, Article  
            can :update, Article do |article|  
              article.try(:user) == user  
            end  
          end  
        end  
      end  
    end
    

    So, in your app if you used this approach, then in your view you could check for current_user.new_record?, and rendering a different "save" button for registered users versus guests.

    You could make this pretty simple (avoiding storing this in session etc.) by providing a hidden account signup form on the sequence creation page. Then just make your "save" button for guests reveal the account creation form, and when they submit that form they're submitting a user registration and a sequence creation at the same time.

    Then all your Sequences#create action needs to do is something like:

    ...
    current_user.update_attributes(params[:user]) if current_user.new_record?
    
    if current_user.sequences.create(params[:sequence])
       redirect_to ...
    else
       render ...
    end
    ...
    

    You'll need to turn that into working code but I'm confident the basic idea would work.

    Good luck!

提交回复
热议问题