我有一个应用程序,您可以在application.html.erb中的标题中登录和注销。登录表单(或注销链接)分别调用用户#signIn或users#signout actions。这两个动作都调用redirect_to root_path。那部分有效。
我想要的是动态更新标头而不是刷新页面(即删除redirect_to)。我想通过javascript / jquery(但不是咖啡)来做到这一点。文件views / users / signIn.js包含三个功能:一个用于用户登录,一个用于管理登录,一个用于用户/管理员登出。
我已经在互联网上搜索过但我无法找到答案。简而言之,在我签署(或注销)用户或管理员之后,我想从signIn.js中包含的users_controller.rb调用javascript / jquery函数(或者对signIn.js.erb,我对此感到困惑)
我的代码如下。谢谢。
users_controller.rb
class UsersController < ApplicationController
include UsersHelper
include AdminsHelper
before_action :correctUser, only: [:edit, :update, :destroy]
...
def signIn
user = User.find_by(email: params[:user][:email].downcase)
if user && user.authenticate(params[:user][:password])
signInUser user
render js: "sUser();" #Call to javascript function
else
admin = Admin.find_by(email: params[:user][:email].downcase)
if admin && admin.authenticate(params[:user][:password])
signInAdmin admin
render js: "sAdmin();" #call to js function
else
flash[:error] = "Invalid email or password"
redirect_to root_path
end
end
end
def signout
#works for both users and admins
signOutUser
render js: "signoutAll();" # call to js function
end
private
def correctUser
redirect_to root_path unless User.find(params[:id]) == currentUser || adminSignedIn?
end
def userParams
params.require(:user).permit(:name, :email,
:password, :password_confirmation)
end
def signInUser(user)
rememberToken = User.newRememberToken
cookies[:remember_token] = rememberToken
#change to cookies.permanent to make cookie stay after browser close
user.update_attribute(:remember_token, User.digest(rememberToken))
end
def signInAdmin(admin)
rememberToken = Admin.newRememberToken
cookies[:remember_token] = rememberToken
#change to cookies.permanent to make cookie stay after browser close
admin.update_attribute(:remember_token, Admin.digest(rememberToken))
end
def signOutUser
#Works for both users and admins
cookies.delete(:remember_token)
end
end
视图/用户/ signIn.js
function sAdmin() {
$("#signin").html("Signed in as Admin \
<%= escape_javascript(link_to currentAdmin.name, currentAdmin)%>. \
<%= escape_javascript(link_to "Sign Out", signout_path)%>");
}
function sUser(){
$("#signin").html("Signed in as User \
<%= escape_javascript(link_to currentUser.name, currentUser)%>. \
<%= escape_javascript(link_to "Sign Out", signout_path)%>");
}
function signoutAll(){
$("#signin").html("blah <%= render 'static_pages/form' %>");
}