我不知所措,想弄清楚为什么我的Rails身份验证管道仅命中new
而不是create
。这将导致登录页面重新呈现,并且永远不会进入search
页面。您能否看一下我的代码以查看我可能忽略的内容?
我正在使用bcrypt
对user
中的密码属性进行哈希处理>
我的routes
Rails.application.routes.draw do root :to => "searches#search" resources :users, only: [:show, :new, :create, :destroy] get '/login', to: 'sessions#new', as: 'login' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy', as: 'logout' get 'searches/index' => "searches#index" get 'searches/show' => "searches#show" get 'searches/search' => "searches#search" get 'audits/show' => 'audits#show' get 'audits/download' => 'downloads#show' post 'audits/' => 'audits#create' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
application_controller
class ApplicationController < ActionController::Base before_action :authorized #lock down this whole app helper_method :current_user #i can call current_user from a view def current_user User.find_by({ id: session[:user_id] }) end def logged_in? !!current_user end def authorized redirect_to login_path unless logged_in? end end
sessions_controller
class SessionsController < ApplicationController skip_before_action :authorized, only: [:new, :create] def new end def create #handles the POST request to /login @user = User.find_by(username: params[:username]) if @user && @user.authenticate(params[:password]) session[:user_id] = @user.id redirect_to @user else flash[:notice] = 'Invalid username or password' redirect_to login_path end end def destroy session.delete(:user_id) flash[:notice] = 'logged out' redirect_to login_path end end
和
sessions/new.html.erb
中的登录表格
<div class='login'> <div class="login-form"> <form> <div class="form-group"> <%= form_with url: login_path, method: 'post', local: true do |f| %> <%= f.label :username, "Username", class: "col-md-4 control-label" %> <%= f.text_field :username, class: "form-control", required: true %> <%= f.label :password, "Password", class: "col-md-4 control-label" %> <%= f.password_field :password, class: "form-control", required: true %> <%= f.submit "Login", class: "btn btn-default btn-primary" %> <% end %> </div> </form> </div> </div>
我也尝试过
form_tag
,但问题相同。我明确指出了该方法,即使没有必要也是如此。
我不知所措,想弄清楚为什么我的Rails身份验证管道仅命中新的而不创建。这将导致登录页面重新呈现,并且永远不会进入搜索页面。请问我的代码...
您可以将routes.rb
更改为:
所以问题是我的Bootstrap form_with
标记中有我的<form>
。默认情况下,表格为get
。