首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails中Globalize3表的简单搜索

Rails中Globalize3表的简单搜索
EN

Stack Overflow用户
提问于 2012-08-22 00:08:15
回答 2查看 2.7K关注 0票数 6

我希望实现一个简单的搜索功能,同时使用Rails的globalize3 gem。由于模型的翻译存储在一个单独的表中,下面的代码无法工作,因为在products表中不再有一个:name字段。如何调整下面的代码以使搜索功能正确?

products_controller.rb

代码语言:javascript
复制
 @products = Product.search(params[:search]).all

index.html.erb

代码语言:javascript
复制
 <%= form_tag products_path, method: :get do %>   
   <%= text_field_tag :search, params[:search] %>
   <%= submit_tag "Search", name: nil %>      
 <% end %>

模型

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-22 00:39:30

你很幸运,我最近处理了同样的问题!

幸运的是,答案很简单。您可以使用类方法with_translations来包含给定区域设置的翻译。

下面是代码:

代码语言:javascript
复制
def with_translations(*locales)
  locales = translated_locales if locales.empty?
  includes(:translations).with_locales(locales).with_required_attributes
end

将其包含在search方法中:

代码语言:javascript
复制
def self.search(search)
  if search
    with_translations.where('name LIKE ?', "%#{search}%")
  else
    with_translations
  end
end

这样就行了。

请注意:您可以向搜索方法中添加一个可选的locales参数,并将其传递给with_translations,以便在特定语言中(例如在当前语言环境中)选择性地缩小搜索范围。

票数 17
EN

Stack Overflow用户

发布于 2020-04-11 12:11:06

解决了..。

代码语言:javascript
复制
    def index
        if params[:search]
          @at = []
          @at = Array.new
          Article.translation_class.where("title LIKE ? OR description LIKE ?","%#{params[:search]}%","%#{params[:search]}%").all.each do |t|
            @at.push t.article_id
          end
          @articles = Article.where(id: @at).recent_first.paginate(page: params[:page], per_page: 5)
        else
          @articles = Article.all.recent_first.paginate(page: params[:page], per_page: 5)
        end
      end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12064756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档