【问题标题】:Using extra search field with rails-jquery-autocomplete使用带有 rails-jquery-autocomplete 的额外搜索字段
【发布时间】:2015-08-17 21:57:09
【问题描述】:

我已经用这个 gem 成功创建了表单:https://github.com/bigtunacan/rails-jquery-autocomplete

问题是我希望它不仅通过源表的 name 字段进行过滤。为此,我尝试使用 gem 文档中提到的 :fields 属性。但呈现的 SQL 仍然包含仅按名称过滤,尽管 GET 请求包含添加字段。

    <%= f.autocomplete_field :name, autocomplete_ad_user_name_component_associated_users_path(@component), 
                                 :update_elements => {:username => '#associated_user_username', 
                                    :password => '#associated_user_password'},
                                    :fields => {:client_id => '#client_id'},
                                    class: 'form-control' %>

我是否需要创建自定义自动完成功能才能使其正常工作?也许我只需要编辑默认创建的函数,但我在哪里可以找到它?

【问题讨论】:

    标签: jquery ruby-on-rails ruby autocomplete


    【解决方案1】:

    您需要定义一个自定义的自动完成方法。

    这应该覆盖get_autocomplete_items 方法。将 ActiveRecord 结果转换为 OpenStruct 也是关键。我在下面提供了一个示例。

      def get_autocomplete_items(parameters)
        result_set = TableName.search do
          fulltext parameters[:term] do
            fields (:first_name)
            fields (:middle_name)
            fields (:last_name)
          end
          order_by (:last_name)
          paginate page: 1, per_page: parameters[:options][:limit]+1
        end.results
    
        new_result_set = []
        hash = {}
    
        # Translating the ActiveRecord object into an OpenStruct is necessary for the rails-jquery-autocomplete
        # Trying to use the ActiveRecord model result directly will result in horrible pain and suffering.
        result_set.each do |r|
          h = {}
          h[:id] = r.id
          h[:email] = r.email_address
          unless hash[r.email]
            new_result_set << OpenStruct.new(h)
            hash[r.email] = true
          end
        end
    
        if new_result_set.empty?
          new_result_set << OpenStruct.new(:email => 'No Match, Search again')
        elsif(result_set.count > parameters[:options][:limit])
          new_result_set << OpenStruct.new(:email => 'Too many results, type more characters')
        end
        new_result_set
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 2016-10-18
      相关资源
      最近更新 更多