Search code examples
ruby-on-railsruby-on-rails-3activerecordpaginationtwitter-typeahead

Autocomplete Vs Pagination


I have a Rails Model with a relatively small number of entries (Currently at ~ 300 and will probably never go past 1000).

It currently paginates items on its index page to show 20 results a page.

I have just added Twitter Typeahead to the search field, and I'm using the record's names to supply the autocomplete suggestions. The problem is that as I'm paginating the results, I'm only able to offer suggestions for the 20 items from the current paginated batch.

The only thing I need from each model is its name, and I don't want to load/parse every record as this will undo most of the advantages from pagination.

So how can I retain sensible pagination, but also access the names of all records in an efficient manner?


Solution

  • You could fetch the names separately with pluck.

    @names = MyModel.pluck(:name)
    

    Note that in Rails 3 you can only provide 1 column name as argument for pluck.

    Pagination usually resorts to LIMIT, so the only way to still retrieve all records, is to do another query.

    With pluck you're only retrieving the field that you want from the database, and you won't have the overhead that ActiveRecord brings when you would go through a complete collection of all your models.