Login/Register with the same submit button in Rails3
I've tried searching everywhere but cannot seem to find an answer.
I am using Authlogic for authentication in my Rails app. I would like to allow users to login or register using the same form, and the same submit action/button. An example of the behavior I am going for is how tumblr handles their login/signup: http://www.tumblr.com/
When a user enters their email address and password, if they already have an account, it logs them into their account dashboard. The same form can be used to create a new blog (with the URL text field).
My actual form is incredibly simple:
= form_for(@user_session) do |f|
= f.text_field :email, :placeholder => "email address"
= f.password_field :password, :placeholder => "password"
= f.submit "get started"
I have tried creating a custom action in the application controller that redirects to the appropriate controller depending on whether the User already exists, but to no avail:
def login_or_register
params[:user] = params[:user_session]
if User.find_by_email(params[:user][:email])
redirect_to :controller => "user_sessions", :action => "create"
else
redirect_to :controller => "users", :action => "create"
end
end
Then, I tried creating a new User if it did not exist from the user_sessions/new
page (inside the UserSessions
controller). Similarly, I tried not creatin开发者_运维百科g a new User and then automatically logging in from the Users
controller. Neither of these approaches worked, and at this time I've reverted my code so I do not have the samples I used.
Any help or advice would be greatly appreciated... thank you so much!
-Z
Imho, the approach where you create user in user_sessions/new if he doesn't exists should work.
It's a pity you don't have your code anymore. Here is one gotcha I can think of: when you create a new user, make sure you make your user active
because Authlogic won't let you to create UserSession
for inactive user.
Also here is a tip: use VCS like git
If you have some new or crazy idea just make a new branch from your master. You do not have to revert anything, just just switch branches and maybe delete them if your crazy_idea branch turned out to be too crazy.
精彩评论