Task To allow the user to select the languages ​​he owns.

User Models

has_many :fluent_languages, foreign_key: 'user_id' accepts_nested_attributes_for :fluent_languages, allow_destroy: true, reject_if: proc { |attributes| attributes['user_id'].blank? || attributes['language_id'].blank? } 

Fluentlanguage

 belongs_to :user belongs_to :language 

Language

 has_many :fluent_languages, foreign_key: 'language_id' 

It would be desirable, that looked here so

My attempt:

 <%= f.fields_for :fluent_languages do |fluent_language| %> <%= fluent_language.text_field :user_id, :type => 'hidden' %> <%= fluent_language.autocomplete_field :language_id, autocomplete_language_language_users_path, 'data-delimiter' => ',', :multiple => true, :placeholder => 'Укажите языки через запятую' %> <% end %> 

Writes in params this

 "7"=>{"user_id"=>"15", "language_id"=>["Английский,"]}} 

and I want the record to be like a regular select:

 "4"=>{"user_id"=>"15", "language_id"=>["1995"], "id"=>"1"} 

Another problem is that the multi-select with autocomplete is output for each entry from fluent_languages. Another problem is that the default values ​​are languages, not names.

How to solve these problems? Or how to solve the problem differently?

  • Immediately the question: why do you need an intermediate table? If only tasks for the sake of the task, but judging by the condition of the problem, you are not going to set the level of language knowledge .... if so I would advise simply to remove the intermediate table. Further, your selection of languages ​​should not fall into language_id , but into language_ids , then when you update the user's record, it will get into the languages ​​that you selected. accepts_nested_attributes_for needed more so that you can create and delete dependent entries, and not just choose. Naturally, do not forget to pass them through strong parameters =)) - Mal Skrylev

0