【问题标题】:Simple search on a Globalize3 table in Rails在 Rails 中对 Globalize3 表进行简单搜索
【发布时间】:2012-08-17 09:11:03
【问题描述】:

我希望在使用 Ruby on Rails 的 globalize3 gem 时实现一个简单的搜索功能。由于模型的翻译存储在单独的表中,因此下面的代码不起作用,因为 products 表中不再有 :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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 search globalize3


    【解决方案1】:

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

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

    【讨论】:

    • 使用 5.0.1 的 gloablize 我得到 'with_required_attributes 已弃用,将在 Globalize 的下一版本中删除。'
    • 在 postgresql 中还需要在列名之前指定表名。
    【解决方案2】:

    解决了...

        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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-24
      • 2015-07-16
      • 2017-12-02
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      相关资源
      最近更新 更多