0

我正在使用 Tire(和 Ryan Bates 的 railscasts)作为站点范围的搜索来实现 Elasticsearch。它搜索多个模型。我希望它按 current_team 过滤。我至少有两个问题:

1) 将过滤器硬编码为“团队 2”不会返回任何结果。在我正在运行的特定查询中,我应该得到两个。我尝试了多种格式的号码、团队等。我尝试过的任何一种方式都不起作用。

2)我不知道如何将 team_id 作为变量传递给过滤器。我尝试像这样发送它:__ .search(params, team),但这导致没有查询结果(这导致我像 #1 一样对团队 ID 进行硬编码)

到目前为止,我已经在 Google 上花费了大约 6 个小时。我得到的最接近的事情是 Karmi 在 github 上对类似问题的回答,基本上说,“阅读手册,它就在那里。” :) 我读过它,作为一个新手,我还是迷路了。

这是现在的代码。

应用程序.html.erb

<bunch of code>

<%= form_tag searches_path, method: :get do %>
  <p>
    <%= text_field_tag :query, params[:query] %>
    <%= submit_tag "Search", name: nil %>
  </p>
<% end %>

<bunch of code>

联系人控制器.rb

class Contact < ActiveRecord::Base
  attr_accessible :address_1, :address_2, :city, :first_name, :last_name, :state, :zip, :team_id
  has_and_belongs_to_many :properties
  belongs_to :user
  belongs_to :team
  has_many :appointments

  before_save :update_name 

  def update_name
    self.name = [first_name, last_name].join(' ')
  end

  #for elastic search
  include Tire::Model::Search 
  include Tire::Model::Callbacks
  def self.search(params)
    tire.search(load: true) do 
      query { string params[:query], default_operator: "AND" } if params[:query].present?
      filter :term, :team_id => ['2']
    end
  end  
end

search_controller.rb

class SearchesController < ApplicationController

  def index
    current_team = :current_team
    @contacts = Contact.search(params)
    @properties = Property.search(params)
   # @events = Event.search(params[:query], load: true)
  end
  def show

  end

end

搜索:index.html.erb:

<div id="content">
  <h1>Search Results</h1>

  <table>
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Last Name</th>
  </tr>

<% @contacts.each do |contact| %>
  <tr>
    <td><%= contact.first_name %></td>
    <td><%= contact.last_name %></td>
    <td><%= contact.team_id %></td>
  </tr>
<% end %>
</table>


  <table>
  <tr>
    <th>Name</th>
    <th>Address 1</th>
  </tr>

<% @properties.each do |property| %>
  <tr>
    <td><%= property.name %></td>
    <td><%= property.address_1 %></td>
  </tr>
<% end %>
</table>



</div>

请注意,Properties 控制器中有类似的搜索功能。我只是想让联系人现在工作。

下面请求的 curl 命令产生:

4

1 回答 1

1

您可以通过参数传递 current_team 值并保留当前搜索方法签名。例如,在您的控制器中:

def index
  params[:current_team] = current_team # method that returns current team ID, are you using devise?
  @contacts = Contact.search(params)
  @properties = Property.search(params)
  # @events = Event.search(params[:query], load: true)
end

在你的模型中:

def self.search(params)
  tire.search(load: true) do 
    query { string params[:query], default_operator: "AND" } if params[:query].present?
    filter :term, params[:current_team] if params[:current_team].present?
  end
end
于 2012-12-02T07:03:18.550 回答