在Rails中的Globalize3表上简单搜索 [英] Simple search on a Globalize3 table in Rails

查看:88
本文介绍了在Rails中的Globalize3表上简单搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在将globalize3 gem用于Ruby on Rails时实现一个简单的搜索功能.由于模型的翻译存储在单独的表中,因此以下代码不起作用,因为产品表中不再存在:name字段.如何调整下面的代码以使搜索功能正确?

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

解决方案

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

幸运的是,答案很简单.您可以使用类方法 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,以可选地将搜索范围缩小为特定语言(例如在当前语言环境中)的字词.

I am looking to implement a simple search function while using the globalize3 gem for Ruby on Rails. Since the translations of the model are stored in a separate table, the code below doesn't work as there is no longer a :name field in the products table. How can I adjust the code below to make the search function correctly?

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 %>

model

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

解决方案

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.

这篇关于在Rails中的Globalize3表上简单搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆