ruby-on-rails - 如何在我的 ConnectionAdapter 回调中使用 Devise 方法?

标签 ruby-on-rails ruby devise

我有一个 Rails 5.1 应用程序,它使用 Devise 处理我的 User 模型的身份验证。这个应用程序有一个 Oracle 数据库后端,需要在执行任何查询之前为登录用户设置一个系统上下文变量,所以我希望在 ConnectionAdapter 的 :checkout 回调中这样做。

class ApplicationController < ActionController::Base
  before_action :log_user

  ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.set_callback :checkout, :after do

    # Would like to get the logged-in user's username here so I can apply 
    # it to the oracle sys_context.

    # The below throws "undefined method 'user_signed_in?'"
    username = current_user.username if user_signed_in?

  end

  def log_user
    # When in this method, user_signed_in? and current_user work fine.
    puts "User is #{current_user.username}" if user_signed_in?
  end
end

user_signed_in? 方法在 :checkout 回调 block 中运行时找不到,尽管它通常在 Controller 中可用。为什么?

此外, block 中的 current_user 似乎计算为 ConnectionAdapter 中定义的 current_user 方法,而不是 Devise 定义的方法。我怎样才能访问 Devise 的 current_user

如何在此回调中使用这些 Devise 提供的方法?

最佳答案

您不能使用 checkout 回调,在它执行时,它与 Controller 上下文没有任何联系。您在 ApplicationController 中定义它的事实与它实际执行的上下文无关。

您需要在 before_action 中设置连接选项,以便在 Controller 上下文中运行。像这样的东西:

before_action :set_user_context

def set_user_context
  if current_user
    ApplicationRecord.connection.execute "DBMS_SESSION.SET_CONTEXT('whatever', 'goes', 'here', '#{current_user.username}')"
  end
end

...或类似的东西。请注意,您可能希望添加一个 checkin 回调以在连接完成时清除该值。

顺便说一句,几天前我回答了一个几乎相同的问题:https://stackoverflow.com/a/54837596/152786虽然命令不同,但可能有所帮助。

关于ruby-on-rails - 如何在我的 ConnectionAdapter 回调中使用 Devise 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54892125/

相关文章:

ruby-on-rails - Belongs_to 和 where 条件

ruby-on-rails - 在 Rails 4 中从头开始构建具有多个收件人的消息传递系统

设计,无法登出

mysql - 在 Ruby on Rails 应用程序中使用 MySQL View 来提高性能

ruby-on-rails - 使用 RubyOnRails 验证 jsonb 对象数组中的对象

ruby-on-rails - 使用RSpec测试密码长度验证

ruby - 如何在没有用户名和密码的情况下访问代理?

ruby-on-rails - rails : Share variables between controller and view

ruby-on-rails - Ruby 中是否有与 slice 函数相反的函数?

ruby-on-rails - 在设计 Rails 中关闭警报消息