Skip to content

Searching - Typeahead Associations

Compare
Choose a tag to compare
@jasonfb jasonfb released this 03 Nov 18:19
· 45 commits to main since this release
05a17b2

The 0.6.x line now begins Hot Glue's foray into searching.

This first stab tackles how to handle foreign keys on the new and edit views only, when looking up a foreign key. Normally foreign keys (associations) are display as drop-downs. You can now use a typeahead when editing any foreign key.

Instead of displaying the foreign key in a drop-down list, the associated record is now selectable from a searchable typehead input.

The typeahead is implemented with a native Stimulus JS pair of controllers and is a modern & clean replacement to the old typeahead options.

  1. As a one-time setup step for your app, run
    bin/rails generate hot_glue:typeahead_install
  2. When generating a scaffold you want to make a typeahead association, use --modify='parent_id{typeahead}' where parent_id is the foreign key
    bin/rails generate hot_glue:scaffold Book --include=title,author_id --modify='author_id{typeahead}'
  3. Within each namespace, you will generate a special typeahead controller (it exists for the associated object to be searched on
    bin/rails generate hot_glue:typeahead Author
    This will create a controller for AuthorsTypeaheadController that will allow text search against any string field on the Author model.
    This special generator takes flags --namespace like the normal generator and also --search-by to let you specify the list of fields you want to search by.

The example Books & Authors app with typeahead is here:

https://github.com/hot-glue-for-rails/BooksAndAuthorsWithTypeahead2

Remember, this typeahead applies only to associations. You can use this feature only on new & edit. You cannot use this feature to search against the list page. Future versions of the 0.6.x line will apply search paradigms to the list page itself.

Hot Glue books and authors with typeahead