How do I use a pg_search_scope with rails-autocomplete-jquery?

806 Views Asked by At

I am using both pg_search and rails-jquery-autocomplete

I have a search scope, powered by pg_search, that is used like this: Node.node_search(query).

I have tried using that method node_search with the autocomplete call on my Node controller, like so:

autocomplete :node, :node_search

But I get an error that there is no column on Node named node_search.

I also tried doing say autocomplete :node, :name, scope: :node_search but that only queries the column node.name. It doesn't actually pass the search query to my Node.node_search like I want.

Basically, what I want to happen is, whenever someone types in 1 or 2 characters, rather than checking the name column or any other column on my Node model, I want it to send that query to Node.node_search (which accepts queries successfully now).

How do I achieve this?

Edit 1

Ideally, I would love to be able to do this without having to do it in JS. If that doesn't exist, I suppose I can use JS. But I would prefer to just use something in the actual rails-jquery-autocomplete gem.

2

There are 2 best solutions below

1
On

You should make your autocomplete send requests to your node_search route :

$("your autocomplete").autocomplete({
  source: function (request, response) {
    $.ajax({
        url: "your endpoint url",
        data: { query: request },
        success: function (data) {
            $this.val(data);
        },
        error: function () {
            alert('oops')
        }
    });
});

});'

0
On

You may try:

autocomplete :node, :node_search, scopes: [:named_scope_1, :named_scope_2, ...]

As it receives an array of scopes and chain them.

You must have your scopes defined in the model:

scope :prospects, -> ()    { where prospect: true }