rails autocomplete gem以限制对语言环境参数的搜索

时间:2019-06-27 10:00:52

标签: ruby-on-rails autocomplete

autcomplete gem调用以下操作进行处理

Started GET "/nations/autocomplete_nationtranslation_name?locale=en&term=erm"

Nationtranslation表具有索引列

t.string   "locale"

模型定义为:

autocomplete :nationtranslation, :nome, full: true
autocomplete :nationtranslation, :nome, full: true, :extra_data => [:locale]

都返回所有语言环境的所有可能值,而

autocomplete :nationtranslation, :nome, full: true, :extra_data => params[:locale]

返回ActionController::RoutingError (undefined local variable or method 'params' for NationsController:Class

如何自动完成在
范围内的搜索   locale = params [:locale]

1 个答案:

答案 0 :(得分:1)

我看到的唯一方法是提供您自己的控制器操作方法,该方法默认是由rails-jquery-autocomplete gem生成的。

class NationsController < ApplicationController

  # you don't really need this anymore
  # autocomplete :nationtranslation, :name

  def autocomplete_nationtranslation_name
    translations = Nationtranslation.where("name LIKE ? AND locale = ?", 
                                           "%#{params[:term]}%", 
                                           params[:locale])
                                    .order(:name)
    render json: translations.map { |t| {id: t.id, label: t.name, value: t.name} }    
  end
end