首页 > 解决方案 > rails 5 algolia search - 按用户状态过滤结果

问题描述

我正在尝试根据当前用户是否具有“管理员”状态来过滤使用 algolia gem 显示的搜索结果。

所有用户都可以创建客户,但“管理员”用户可以访问所有客户,无论他们是否由该用户创建。我还在为我的“用户”模型使用设计 gem。

客户控制器:

def index
  if current_user.admin
    @customers = Customer.all.order(id: :desc).paginate(:page => params[:page], :per_page => 4)
  else
    @customers = Customer.where(user: current_user).order(id: :desc).paginate(:page => params[:page], :per_page => 4)
  end
end

我正在使用 algolia rails gem 来搜索客户中的客户#index

搜索JS:

<!-- Algolia search JS -->
<script>
  var client = algoliasearch('x', 'x');
  var index = client.initIndex('Customer');
  //initialize autocomplete on search input (ID selector must match)
  autocomplete('#aa-search-input',
{ hint: false }, {
  source: autocomplete.sources.hits(index, {hitsPerPage: 5}),
  //value to be displayed in input control after user's suggestion selection
  displayKey: 'name',
  //hash of templates used when rendering dataset
  templates: {
      //'suggestion' templating function used to render a single suggestion
      suggestion: function(suggestion) {
        return `<span>${suggestion.first_name.value}"</span>` +;
      }
    }
  });
</script>

我需要做的是根据登录用户是否是“管理员”用户来过滤自动完成建议。这只需要过滤该特定会话的索引,以便同时登录的多个用户不会影响其他用户可用的客户索引。

标签: ruby-on-railsdeviseruby-on-rails-5algolia

解决方案


按照设计,Algolia 不是关系数据库。

它不知道是哪个user has_many customers,还是那个customer belongs_to user。它也不了解 Devise 并且用户是管理员。

要在 Algolia 中复制这种关系,您必须创建一个“平面对象”,将关系保存在属性中。

例如,您的“客户”索引可能包含属性列出可以查看它们的记录。您可以调用它viewable_byuser_ids,任何您想要的(如果您没有“用户”索引,那么这些可能id来自您的数据库,无论工作如何):

// sample Customer record in Algolia
{
    "name": "Ricky Bobby",
    "viewable_by": [1, 55, 278]
}

接下来,我将依靠您从 Rails 传递您的current_user.admin(true/false) 和用户id,以便您可以在 JS 条件中引用它。

然后在自动完成中创建一组条件参数。如果current_user.adminfalse则过滤用户id

<!-- Algolia search JS -->
<
script >
  var client = algoliasearch('BFBCTI275G', '5818cd87afb6c0ef5e4d5ec4ed6580d0');
var index = client.initIndex('Customer');

// create variable
var srcParams = {
  hitsPerPage: 5
}

// conditionally set filter based on admin
// your job to get admin boolean and user id into JS
if (!current_user.admin) {
  srcParams.filters = 'viewable_by: current_user.id';
}

autocomplete('#aa-search-input', {
  hint: false
}, {
  // use the srcParams
  source: autocomplete.sources.hits(index, srcParams),
  displayKey: 'name',
  templates: {
    suggestion: function(suggestion) {
      return `<span>${suggestion.first_name.value}"</span>` + ;
    }
  }
}); <
/script>


推荐阅读