You're not supposed to "fetch the data attributes" on the server side in Ruby/Rails. You set these values in Rails.
Why?
Think of a separation of concerns (bear with me, this is a very high level abstraction):
- Rails "just" delivers the HTML and Javascript files
- the HTML defines the structure of the things you'd like to present
- the Javascript defines the behavior of the different things
- with data attributes you get an easy and standardized way to parameterize the behavior without hard coding value into your Javascript
Since you are in control when generating the HTML code (i.e. generating data attributes) you could just write generic Javascripts and leverage the parameterization to the data attributes.
In your form example, you would still use basic input fields, like so:
<%= form_tag url: foobar_path do %>
<div class="container-data">
<%= text_field_tag :all, placeholder: 'Tutto' %>
<%= text_field_tag :author, data: { facet: 'autocomplete', url: authors_path(format: :json) }, placeholder: 'Autore' %>
<%= text_field_tag :category, data: { facet: 'autocomplete', url: categories_path(format: :json) }, placeholder: 'Categoria' %>
<%= text_field_tag :isbn, data: { facet: 'isbn' }, placeholder: 'ISBN' %>
</div>
<%= submit_tag 'Invia', class: 'search_submit' %>
<% end %>
and use could use the data-facet attribute to initialize some kind of additional behaviour, like autocompletion or format validation (I'd admit this is a constructed example):
$(document)
.on('change keyup', '[data-facet="isbn"]', function(event){
var value = $(this).val() // e.g. validate
})
.on('change keyup', '[data-facet="autocomplete"]', function(event){
var value = $(this).val(),
url = $(this).data('url') // use `url` to fetch auto completion suggestions
})