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
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!
I'm also working on a rails 3 project w/ devise and cancan. My needs are a little different in that I need to persist anonymous users' activity in the db (no need to sweep). Here's what I did to sign in the anonymous user. Hope this helps.
def sign_in_anonymous_user
unless user_signed_in?
user = User.new
role = "anonymous"
user.confirmed_at = Time.now-1.minute
user.save :validate => false
sign_in :user, user
end
end