ruby-on-rails 如何在globalize中使用pg_search?

4c8rllxm  于 2023-10-21  发布在  Ruby
关注(0)|答案(2)|浏览(92)

我使用pg_search gem在我的rails应用程序中进行搜索。我的应用程序中的主要模型是:

class Book < ActiveRecord::Base
  include PgSearch
  pg_search_scope :search_everywhere, against: [:author, :title, :description]
end

它工作完美,

@books = Book.search_everywhere(params[:search])

在BooksController的索引操作中。然后我添加了gem 'globalize':

translates :title, :author, :publisher, :description, :fallbacks_for_empty_translations => true

现在搜索不起作用。

Book.search_everywhere(params[:search])

找不到场地。有人在globalize gem中使用pg_search gem吗?

kd3sttzy

kd3sttzy1#

我找到了正确的解决方法:Gem 'globalize'创建了新表“book_translations”。所以我应该在这个表中搜索:

#book.rb
class Book < ActiveRecord::Base
  include PgSearch
  has_many :book_translations
  translates :title, :author, :publisher, :description, :fallbacks_for_empty_translations => true
  pg_search_scope :search_everywhere, :associated_against  => {:book_translations => [:title, :author, :description]}
end

#book_translation.rb
class BookTranslation < ActiveRecord::Base
  belongs_to :book
end
zzzyeukh

zzzyeukh2#

您不需要创建BookTranslation模型。这里有一个更简单的解决方案:

class Book < ActiveRecord::Base
  include PgSearch
  translates :title, :author, :publisher, :description, :fallbacks_for_empty_translations => true
  pg_search_scope :search_everywhere, :associated_against  => {:translations => [:title, :author, :description]}
end

相关问题