Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Rails中对Globalize3表进行简单搜索_Ruby On Rails_Ruby On Rails 3_Search_Globalize3 - Fatal编程技术网

Ruby on rails 在Rails中对Globalize3表进行简单搜索

Ruby on rails 在Rails中对Globalize3表进行简单搜索,ruby-on-rails,ruby-on-rails-3,search,globalize3,Ruby On Rails,Ruby On Rails 3,Search,Globalize3,我希望在使用RubyonRails的Globalize3Gem时实现一个简单的搜索功能。由于模型的翻译存储在一个单独的表中,下面的代码不起作用,因为products表中不再有:name字段。如何调整下面的代码以使搜索功能正确 产品\u controller.rb @products = Product.search(params[:search]).all <%= form_tag products_path, method: :get do %> <%= t

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

产品\u controller.rb

 @products = Product.search(params[:search]).all
 <%= form_tag products_path, method: :get do %>   
   <%= text_field_tag :search, params[:search] %>
   <%= submit_tag "Search", name: nil %>      
 <% end %>
index.html.erb

 @products = Product.search(params[:search]).all
 <%= 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
类产品
你很幸运,我最近解决了完全相同的问题

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

代码如下:

def with_translations(*locales)
  locales = translated_locales if locales.empty?
  includes(:translations).with_locales(locales).with_required_attributes
end
将其包括在您的
搜索方法中:

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

作为补充说明:您可以向搜索方法添加可选的
locales
参数,并通过翻译将其传递给
,以选择性地将搜索范围缩小到特定语言的术语,例如当前语言环境中的术语。

已解决

    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

使用gloablize I get的5.0.1“with_required_attributes”已被弃用,并将在下一版本的Globalize中删除。在postgresql中,还需要在列名之前指定表名。