gpt4 book ai didi

ruby - 设计 - 使用 Ajax 登录

转载 作者:数据小太阳 更新时间:2023-10-29 06:51:04 26 4
gpt4 key购买 nike

是否有可能为 ajax 通信修改设计 SessionsController

编辑

我找到了解决方案,并将其发布到答案中,谢谢

最佳答案

1。生成 Devise Controller 以便我们修改它

rails g devise:controllers

enter image description here

现在我们在 app/controllers/[model] 目录 中拥有所有 Controller

2。编辑 routes.rb

让我们将 Devise 设置为使用我们修改后的 SessionsController

首先将此代码(当然将:users更改为您的设计模型)添加到config/routes.rb

devise_for :users, controllers: {
sessions: 'users/sessions'
}

3。修改session_controller.rb

enter image description here

找到create方法改成

def create
resource = User.find_for_database_authentication(email: params[:user][:email])
return invalid_login_attempt unless resource

if resource.valid_password?(params[:user][:password])
sign_in :user, resource
return render nothing: true
end

invalid_login_attempt
end

protected之后创建新方法

def invalid_login_attempt
set_flash_message(:alert, :invalid)
render json: flash[:alert], status: 401
end

4。设计.rb

将其插入config/initializers/devise.rb

config.http_authenticatable_on_xhr = false
config.navigational_formats = ["*/*", :html, :json]

5.无效的电子邮件或密码消息

sessions 下的 config/locales/devise.en.yml 中插入一条新消息

invalid: "Invalid email or password."

sessions

6。查看

= form_for resource, url: session_path(:user), remote: true do |f|
= f.text_field :email
= f.password_field :password
= f.label :remember_me do
Remember me
= f.check_box :remember_me
= f.submit value: 'Sign in'

:javascript
$(document).ready(function() {
//form id
$('#new_user')
.bind('ajax:success', function(evt, data, status, xhr) {
//function called on status: 200 (for ex.)
console.log('success');
})
.bind("ajax:error", function(evt, xhr, status, error) {
//function called on status: 401 or 500 (for ex.)
console.log(xhr.responseText);
});
});

Important thing remote: true

与 {status: 'true'} 不同,我使用 status 200 或 401 的原因是数据量较小,因此速度更快、更干净。

说明

登录时,您会在参数中获取这些数据

action: "create"
commit: "Sign in"
controller: "users/sessions"
user: {
email: "test@test.cz"
password: "123"
remember_me: "0"
}
utf8: "✓"

在签名之前,您需要对用户进行授权。

resource = User.find_for_database_authentication(email: params[:user][:email])

User.find_for_database_authentication

如果找到用户,资源将被填充类似

created_at: "2015-05-29T12:48:04.000Z"
email: "test@test.cz"
id: 1
updated_at: "2015-06-13T19:56:54.000Z"

否则会是

null

如果用户通过了身份验证,我们将要验证他的密码

if resource.valid_password?(params[:user][:password])

最后登录

sign_in :user, resource

来源

SessionsController

帮助了我 Andreas Lyngstad

关于ruby - 设计 - 使用 Ajax 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30829225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com