在Rails上搜索Elasticsearch(gem Tire)中包括其他表

时间:2014-05-15 20:51:14

标签: ruby-on-rails ruby elasticsearch tire

我有模特书和作者,我想制作一些作者和作者。表加载使用include方法同时我使用elasticsearch(轮胎)。让我展示代码。

这是我的控制人员:

  def index
    @books = Book.search(params)
  end

和我的模特:

class Book < ActiveRecord::Base
  has_and_belongs_to_many :authors

  include Tire::Model::Search
  include Tire::Model::Callbacks

  mapping do
    indexes :id
    indexes :title, analyzer: 'snowball'
    indexes :summary, analyzer: 'snowball'
    indexes :released_at, type: 'date'
    indexes :edition
    indexes :isbn, analyzer: 'keyword'
    indexes :authors_name
    indexes :author do
      indexes :id
      indexes :name
    end

  end

  def self.search(params)
    tire.search(load: true) do
      query { string params[:query] } if params[:query].present?
    end
  end

  def authors_name
    authors.all
  end

  # Needed to be searchable
  def to_indexed_json
    to_json( include: { authors: { only: [:name] } } )
  end

end

视图和rails日志:

<%= book.authors_name.map {|a| link_to a.name, author_path(a.id) }.join(', ').html_safe %>


tarted GET "/books?utf8=%E2%9C%93&query=&commit=Search" for 127.0.0.1 at 2014-05-15 17:38:58 -0300
Processing by BooksController#index as HTML
  Parameters: {"utf8"=>"✓", "query"=>"", "commit"=>"Search"}
  Book Load (0.2ms)  SELECT "books".* FROM "books"  WHERE "books"."id" IN (2, 1)
  Author Load (0.2ms)  SELECT "authors".* FROM "authors" INNER JOIN "authors_books" ON "authors"."id" = "authors_books"."author_id" WHERE "authors_books"."book_id" = ?  [["book_id", 2]]
  Author Load (0.1ms)  SELECT "authors".* FROM "authors" INNER JOIN "authors_books" ON "authors"."id" = "authors_books"."author_id" WHERE "authors_books"."book_id" = ?  [["book_id", 1]]
  Rendered books/index.html.erb within layouts/application (11.2ms)
Completed 200 OK in 69ms (Views: 62.7ms | ActiveRecord: 0.5ms)

但直到现在我还没有成功。我有办法吗?

1 个答案:

答案 0 :(得分:1)

我做到了!

因为我已经加载了作者的索引:

indexes :author do
  indexes :id
  indexes :name
end

我只需确保通过json发送id和名称:

def to_indexed_json
  to_json include: :authors
end

然后我可以在视图中执行此操作:

<span>By <%= book.authors.map { |a| link_to a.name, author_path(a.id) }.join(', ').html_safe %></span>

我从代码中删除了load:true,这使得页面加载速度更快。