简体   繁体   English

包括有关在Elasticsearch on Rails(Gem Tire)上搜索的其他表格

[英]Include other table on Search of Elasticsearch on Rails (gem Tire)

I have the models Book and Author and I'd like to make the rows of Authors' table load using includes method at the same time I use elasticsearch (tire). 我有Book和Author模型,我想在使用Elasticsearch(轮胎)的同时使用include方法使Authors表的行加载。 Let me show the code. 让我显示代码。

Here's my controller: 这是我的控制器:

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

and my Model: 和我的模特:

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

That's the view and rails log: 那是视图和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)

But till now I didn't manage to it. 但是直到现在我还是没有做到。 Is there a way I can do it? 有办法吗?

I made it! 我做到了!

As I already loaded the authors' indexes: 我已经加载了作者的索引:

indexes :author do
  indexes :id
  indexes :name
end

I just needed to make sure id and name were send via json: 我只需要确保id和name是通过json发送的:

def to_indexed_json
  to_json include: :authors
end

Then I can do this in the view: 然后,我可以在视图中执行此操作:

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

And I removed load: true from the code which makes the page load pretty much faster. 我从代码中删除了load:true,这使得页面加载快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM