在我的rails应用中,有很多页面都不需要您登录才能查看。例如,某个用户的个人资料页面。我当前的会话逻辑会重定向回上一页,如果该页面要求您登录。如果它没有,例如个人资料页面,并且您单击登录并登录,它只会将您带到网址在我的SessionsController操作中指定。这让我走到了一个十字路口。要么我需要一个模式在每个页面上(在layouts/application.html.erb
中)都有会话形式,以便用户可以单击登录,模型将打开,当他们登录时只需刷新页面,以便用户可以留在当前页面。但是,我现在正在尝试并获得一些错误。另一个选项是拥有单独的登录页面,但无论您在应用程序中来自哪个页面,它都会将您重定向回。不幸的是,我不确定如何为此编写代码。
以下是我目前的代码,我试图通过模式在每个页面上设置Session表单。
**SessionsController #create action**
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_back_or request.original_url
else
flash.now[:error] = "Invalid email/password combination."
render 'new'
end
end
**layouts/application.html.erb**
<% unless signed_in? %>
...modal code
<%= form_for(:session, url: sessions_path) %>
<%= text_field ... %>
<%= password_field .... %>
<%= submit button %>
<% end %>
... # I've shorted the code here obviously
<% end %>
此表单在/login
页面上正常工作:match '/login', to: "sessions#new", via: "get"
但是,当我在其他页面上使用此表单时,我收到此错误:
`Missing template public/error with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. `
,这个页面就是这样的:
http://localhost:3000/sessions
如何让这个Sessions表单在网站的每个页面上都能正常工作?感谢
更新
在使用它之后,我意识到当我将SessionController中的代码更改为
时,表单可以正常工作redirect_back_or profile_path(user)
而不是当前的
redirect_back_or request.original_url
如何重定向回到当前页面,而不是像配置文件页面那样指定特定页面???
答案 0 :(得分:0)
我想我找到了答案。如果你有更好的解决方案,请仍然回答。
redirect_back_or :back