Reputation: 45
I am trying to use the same code that I used in rails 3 for sessions.
def create
user = User.find_by_name(params[:name])
if user && user.authenticate(params[:password])
session[:user_id] = user.id #stores the id in the session
redirect_to user #displays the user/show view
else
flash.now[:error] = "Invalid name/password combination."
render 'new'
end
end
I have adjusted it to
def create
user = User.find_by_username(params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id #stores the id in the session
redirect_to user #displays the user/show view
else
flash.now[:error] = "Invalid name/password combination."
render 'new' #shows the signin page again
end
end
But I am now getting the error:
"SyntaxError in SessionsController#new"
/sessions_controller.rb:5: syntax error, unexpected tIDENTIFIER, expecting keyword_then or ';' or '\n' ...te(params[:password]) session[:user_id] = user.id
I'm sure it is to do with the fact I am using rails 4 now and not 3 and there is some syntax that is not compatible with 4, but I can't seem to work it out.
Upvotes: 0
Views: 302
Reputation: 685
You cannot use the body of an if statement on the same line as the condition unless you separate it from the condition with the keyword then
. Here I have tidied your code, so there is a line break after the condition.
def create
user = User.find_by_username(params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id # stores the id in the session
# displays the user/show view
else
flash.now[:error] = "Invalid name/password combination." # Shows the sign in page again
redirect_to user
end
end
Upvotes: 2