認証が成功するかどうかを確認するログインページがあります。httpポスト失敗後にブラウザのURLが変更される
<%=form_with scope: :session, url: sessions_path, local: true, html: {class: "login-form"} do |f| %>
<%= f.label :email, t("session.new.email") %>
<%= f.email_field :email %>
<%= f.label :password, t("session.new.password") %>
<%= f.password_field :password %>
<%= f.submit t('session.new.login'), class: "submit" %>
<% end %>
それはsessions_controller.rb
に関連付けられている、以下の通りである:ここではページnew.html.erb
である私のroutes.rb
で
class SessionsController < ApplicationController
def create
# Find the user with the matching email
user = User.find_by(email: params[:session][:email].downcase)
# Check the user exists in DB and that the provided password matches
if user && user.authenticate(params[:session][:password])
# Log the user through the session helper
log_in user
# Redirect to the hive
redirect_to ideas_path
else
# The authentication failed. Display an error message
flash.now[:error] = I18n.t('session.new.invalid_credentials')
# The render is done to reinitiate the page
render :new
end
end
end
が、私は、この目的のために持っている:
resources :sessions
rails routes
を実行すると、次の宣言ルートがあります。
これでログインに失敗しました。私のコントローラでは、この場合、フラッシュメッセージにメッセージを追加し、同じページを再度レンダリングしますnew.html.erb
。しかしブラウザでは、ログインリクエストPOSTはURL /sessions
に送られました。問題は、ブラウザの現在のURLが/sessions/new
の代わりに/sessions
になっていることです。 POSTリクエストによってブラウザのURLが変更されたようです。しかし、これは実際にはAJAXリクエストです。
私は、私は回避策を発見した
(私は著者ではないよ)、この現象について同じ疑問に思うこのblog postを発見したが、私はそれを使用することは避けてくださいを好むとbevahiorを理解するだろう。私は、次のことで、私のルートを交換する場合は、この作品:
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
この作品、なぜ私が理解することができます:GETとPOSTのURLが同じなので、ブラウザはそのURLを変更しません。
ご存知ですか?
EDIT:
私は最終的に解決策を見つけました。私はこれが "レールの道"であるかどうかはわかりませんが、これは期待通りに機能します。
フォームがブラウザを提出しますdef create
# Find the user with the matching email
user = User.find_by(email: params[:session][:email].downcase)
# Check the user exists in DB and that the provided password matches
if user && user.authenticate(params[:session][:password])
# Log the user through the session helper
log_in user
# Redirect to the hive
redirect_to ideas_path
else
# The authentication failed. Display an error message through a flash
# message after redirect to the same page
redirect_to new_session_path, alert: I18n.t('session.new.invalid_credentials')
end
end
回答とその関連文書をありがとうございます。私が見逃している点があります:POSTリクエストを送信すると、ブラウザのURLが変わるのはなぜですか?私はこれがGETリクエストの場合にすぎないはずだと思いました。 Furthemore、私のユースケースではRoRの良いアプローチは何ですか? –
これは、私よりもはるかに説明するための適切な文書を見つけることを試みましたが、運はありません。ブラウザは '/ sessions/new'を訪れます。その後、フォームを送信するので、ブラウザが知っている最後のURLは '/ sessions'です。これがサーバーから要求された "リソース"です。サーバーは応答し、リダイレクトしないため、ブラウザはそのURLを使用します。ブラウザで開発ツールを開き、サーバーの応答を確認します。応答URLは '/ sessions'です。それが意味をなさないことを願っています:/ – gkats
はい、あなたの答えは理解するのを助けました。今、私は目標を達成できるようにRailsを正しく使う方法を理解する必要があります:) –