In my Rails app, if the user is trying to create a new account, and already has a session going (i.e. is logged in), I want to display a message that says "It looks like you already have an account".
To do this, I'm trying to check for a current session with the following code:
<% if session[:user_id]? %>
<div id="error_expanation">Seems like you already have an account with us.
<% link_to "Sign in now", login %></div>
<% end %>
However, this code results in the following error:
compile error
/path/to/app/views/users/_form.html.erb:17: syntax error, unexpected ';'
');@output_buffer.safe_concat(' ...
^
/path/to/app/views/users/_form.html.erb:42: syntax error, unexpected kENSURE, expecting $end
I'm pretty sure is the 'session[:user_id]?' that's causing the problem, because if I replace it with something from another if statement, it works.
Any idea on what I need to fix to check for this? Thanks!
Oh, and here's my sessions_controller.rb if it's needed:
class SessionsController < ApplicationController
def edit
session[:return_to] = request.referer
end
def new
end
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
session[:user_name] = user.name
redirect_to admin_url
else
redirect_to login_url, :alert => "Invalid username / password combination"
end
end
def destroy
session[:user_id] = nil
redirect_to admin_url, notice => "You've successfully logged out."
end
end
I would suggest changing this line:
<% if session[:user_id]? %>
to
<% if session[:user_id] %>
That should fix the problem. The cleaner solution would be to add a function call to your application controller like this:
class ApplicationController
def user_is_logged_in?
!!session[:user_id]
end
end
Then you could do the following:
<% if user_is_logged_in? %>
I would strongly urge you to use something like Device for login logic, as it'll be more secure than any roll-your-own-code. Then you can do something like: <%= dowhatever if user_signed_in? %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With