首页 文章

如何通过current_team过滤Tire?

提问于
浏览
0

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

1)将过滤器硬编码为“团队2”会导致无结果 . 在我运行的特定查询中,我应该得到两个 . 我尝试了各种格式的数字,团队等等 . 我没有尝试过任何工作 .

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

到目前为止,我已经在Google上花了大约6个小时 . 我最接近的是Karmi对github上类似问题的回应,该问题主要是说“阅读手册,就在那里” . :)我已经阅读了它,并且作为一个新手,我仍然迷失了 .

这是现在的代码 .

application.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>

contacts_controller.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

searches_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>

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

下面要求的curl命令产生:

1 回答

  • 1

    您可以通过params传递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
    

相关问题