Simple search on a Globalize3 table in Rails

…衆ロ難τιáo~ 提交于 2019-12-03 16:09:35

You're in luck, I tackled exactly the same problem recently!

Luckly for you the answer is quite simple. You can use the class method with_translations to include translations for a given set of locales.

Here's the code:

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

Include it in your search method:

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

That should do it.

As an added note: you could add an optional locales parameter to the search method and pass it to with_translations to optionally narrow the search to terms in a particular language, say for example in the current locale.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!