Link
Link

Reputation: 43

Using extra search field with rails-jquery-autocomplete

I have succesfully created forms with this gem: https://github.com/bigtunacan/rails-jquery-autocomplete

The problem is that I would like it to filter not only by name field of source table. For that I tried to use :fields attribute as mentioned in gem's documentation. But rendered SQL still contains filtering only by name, although GET request contains added field.

    <%= 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' %>

Do I need to create custom autocomplete function for this to work or what? Maybe I just have to edit by default created function, but where can I find it?

Upvotes: 2

Views: 336

Answers (1)

bigtunacan
bigtunacan

Reputation: 4986

You would need to define a custom autocomplete method.

This should override the get_autocomplete_items method. It is also key that you convert your ActiveRecord results to an OpenStruct. I've included a sample below.

  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

Upvotes: 1

Related Questions