-->

在Rails中Globalize3表简单搜索(Simple search on a Globaliz

2019-07-31 03:15发布

我期待,而使用Ruby on Rails的在globalize3宝石实现一个简单的搜索功能。 由于模型的翻译都存储在一个单独的表,下面的代码不能正常工作,因为不再是:在产品表名称字段。 我怎样才能调整下面的代码正确地使搜索功能?

products_controller.rb

 @products = Product.search(params[:search]).all

index.html.erb

 <%= form_tag products_path, method: :get do %>   
   <%= text_field_tag :search, params[:search] %>
   <%= submit_tag "Search", name: nil %>      
 <% end %>

模型

class Product < ActiveRecord::Base
  translates :name
  attr_accessible :name, :price, :released_at

  def self.search(search)
    if search
      where('name LIKE ?', "%#{search}%")
    else
      scoped
    end
  end
end

Answer 1:

你很幸运,我最近解决了完全相同的问题!

Luckly你的答案非常简单。 您可以使用类方法with_translations包括一组给定的语言环境的翻译。

下面的代码:

def with_translations(*locales)
  locales = translated_locales if locales.empty?
  includes(:translations).with_locales(locales).with_required_attributes
end

它包括在你search方法:

def self.search(search)
  if search
    with_translations.where('name LIKE ?', "%#{search}%")
  else
    with_translations
  end
end

这应该这样做。

作为一个补充说明:你可以任意添加locales参数的搜索方法,并把它传递给with_translations有选择地缩小特定语言的搜索条件,例如说在当前的语言环境。



文章来源: Simple search on a Globalize3 table in Rails