lundi 11 mai 2015

Rails/JS/JQuery multiple select with suggestions, custom values and ids

I have, for example, project and category models:

# project.rb
has_and_belongs_to_many :categories

# category.rb
has_and_belongs_to_many :projects

In the front-end I need to:

  • Show input for name of the project category
  • Suggest / autocomplete category by name if it exist
  • If it doesn't exists, I need to dynamically create it and paste name into input and hold ID, then send ID to server when user submits form.

So, I have categories controller, which have methods search and create. Search returns in JSON format pairs of ID and NAME of suggested categories; create saves category into database and returns pair of ID and NAME when user submits new category into input. It is about multiple category input.

Also, in other part of website we could meet models, that uses category model not as has_and_belongs_to, but as belongs_to. There I need to show select box with single value of category, but with the same logic with multiple input.

Select2 or selectize libs covers most part of my issue, but I have no idea how to hold IDs instead of names into input and how to render name of category into input and send ID when user submits form.

Are there any libs or technics to solve this issue? The question is mostly about JS/Front-end.

Thanks.

Aucun commentaire:

Enregistrer un commentaire