首页 > 解决方案 > Rails 5:将 HTTParty 查询限制为 current_user

问题描述

我目前正在实现 Typeform 的 API。我能够获取响应,但我需要向用户显示响应分配。

当一个 typeform 被提交时,一个hidden_field被传递给 Typeform 这是current_user.hash_id.

到目前为止一切都很好。我还可以使用parameter调用的 API 设置限制query

所以我的请求目前看起来像:

  def get_data
    self.class.get("/forms/XXXXX/responses?page_size=25&query=", headers: { "Authorization" => @auth})
  end

我需要添加current_user.hash_id到.&query=current_user

因此,我应该将逻辑传递给 mycontroller以使其current_user易于访问,还是有另一种方法可以current_user安全地调用 my model

标签: ruby-on-rails

解决方案


导轨 5.2

所以我做了以下事情:

我创建了一个module访问lib权限:user

module Current
 thread_mattr_accessor :user
end

后来我把这个添加到我的ApplicationController

around_action :set_current_user

def set_current_user
  Current.user = current_user
  yield
 ensure
  Current.user = nil
 end

您还需要添加config.autoload_paths到您的àpplication.rb

config.autoload_paths += %W(#{config.root}/lib)

之后,您需要重新启动服务器。

最后,您可以访问Current.user您的模型,例如:

  def get_data
    self.class.get("/forms/XXXXX/responses?page_size=25&query=#{Current.user.hash_id}", headers: { "Authorization" => @auth})
  end

推荐阅读