---
# System prepended metadata

title: '[Rails4][Controller]處理用戶登入時系統強制轉向問題'
tags: [controller, Rails4]

---

# [Rails4][Controller]處理用戶登入時系統強制轉向問題


###### tags: `Rails4`,`controller`

2019/12/22
今天在練習進度條線上課程遇到一個問題,
在做使用者登入時,若輸入不存在的使用者名稱,
系統會強制導向以該post方法為名稱的view.


routes:
```ruby
Rails.application.routes.draw do
  
  #...
  get "users/login"=>"users#login"
  post "users/create_session"=>"users#create_session"
  
  get "users/logout"=>"users#logout"
  
  #...
end

```
controller:

```ruby
class UsersController < ApplicationController
  def login
  end

  def create_session
    #pass params[:account] from view
    #use this params to find user by name or email
    #so that user can login by email or name
    @user=User.find_by(name: params[:name],password: params[:password])
    
    if @user
     flash[:notice]=@user.name
     redirect_to root
    else
     render "login"
    end
    
  end

  #...
end

```

view就是一個簡單的form,會傳回帳號密碼.

現在的問題在於,

上面的寫法若遇到用戶輸入不存在的使用者,
則系統會強制以get的方式重新導向名稱為create_session.html.erb的view,非常奇怪.


解決方式:
加上判斷式,讓系統導向特定view

```ruby
class UsersController < ApplicationController
#...

  def create_session
  
    #pass params[:account] from view
    #use this params to find user by name or email
    #so that user can login by email or name
    @user=User.find_by(name: params[:account])|| User.find_by(email: params[:account])
    if !@user || !check_password(@user.password,params[:password])
      render "users/login" 
    else
      flash[:notice]=@user.name
      redirect_to root_path
    end
    
      private 
      def check_password(db_password,input_password)
        db_password == input_password

      end

    
  end
  
#...

end
```


