A minimal Rails app demonstrating the new f.datalist FormBuilder helper, which
wires a text input to a native HTML <datalist> for autocomplete with zero
JavaScript and no derived-id bookkeeping.
It's the companion code for the Code With Rails post:
Build Native Autocomplete in Rails Forms with f.datalist (No JavaScript)
f.datalistis on Railsmain(slated for 8.2) but not yet in a released version, so this app'sGemfilepointsrailsat the GitHubmainbranch (rails/rails#57318). Swap that for a version once 8.2 ships.
app/views/profiles/new.html.erb has two autocomplete fields:
- Country -- suggestions from a hardcoded list (
Profile::COUNTRIES) - Tag -- suggestions pulled from the database (
Profile.suggested_tags)
Both use the pattern from the post:
<%= f.text_field :country, list: f.field_id(:country, :datalist) %>
<%= f.datalist :country, Profile::COUNTRIES %>The input's list: and the datalist's id are both
field_id(:country, :datalist), so they stay wired together with no manual id
bookkeeping.
bundle install
bin/rails db:setup # create, migrate, and seed
bin/rails serverThen open http://localhost:3000, click into Country or Tag, and start typing -- the browser shows native suggestions with no JavaScript.
Create a few profiles with new tags, then reload the form: your tags show up in the Tag suggestion list (DB-backed choices).
- Routes:
/(new profile form),/profiles(list) - To reset the data:
bin/rails db:reset - Native
<datalist>dropdowns are rendered by the OS, so they show up in a real browser but not in automated screenshots.