在 Sessions#controller 中获取语法错误

Getting a syntax error in Sessions#controller

我正在尝试使用我在 rails 3 中用于会话的相同代码。

 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

我已经调整为

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

但我现在收到错误消息:

"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

我确定这是因为我现在使用的是 rails 4 而不是 3,并且有些语法与 4 不兼容,但我似乎无法使用它出来了。

您不能将 if 语句的主体与条件放在同一行,除非您使用关键字 then 将其与条件分开。这里我已经整理了你的代码,所以条件后面有一个换行符。

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