我希望实现一个简单的搜索功能,同时使用Rails的globalize3 gem。由于模型的翻译存储在一个单独的表中,下面的代码无法工作,因为在products表中不再有一个:name字段。如何调整下面的代码以使搜索功能正确?
products_controller.rb
@products = Product.search(params[:search]).allindex.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发布于 2012-08-22 00:39:30
你很幸运,我最近处理了同样的问题!
幸运的是,答案很简单。您可以使用类方法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,以便在特定语言中(例如在当前语言环境中)选择性地缩小搜索范围。
发布于 2020-04-11 12:11:06
解决了..。
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
endhttps://stackoverflow.com/questions/12064756
复制相似问题