Вопрос

This may be a variant of unanswered Select2-rails passing data to form field

I have a field barrister_id in a form

<%= form_for(@mail) do |f| %>
  ...
  <div class="field">
    <%= f.label :barrister_id %><br />
    <!-- %= f.collection_select :barrister_id, Barrister.all, :id, :code_and_name % -->
    <% @barristers = Barrister.all %>
    <%= select_tag :barrister_id,   options_from_collection_for_select(@barristers,
      :id,:code), id: "barristerselect"%>
  </div>

The application.html.erb links this to javascript Select2 gem thus:

<script>
  $(document).ready(function() { $("#barristerselect").select2(); });
</script>

and that works to give me the fancy Select2 pulldown of values.

BUT the field value barrister_id is returned only in params.barrister_id, NOT as expected in params.mail.barrister_id, so that the value entered fails validation as being blank.

As shown commented out, I would have preferred to use f.collection_select for the selection box, but couldn't get Select2 to work nice with it.

Any ideas folks?

Это было полезно?

Решение

First of all you should use f.select in this case. With select_tag you need to do this

<%= select_tag "mail[barrister_id]",   options_from_collection_for_select(@barristers,
  :id,:code), id: "barristerselect"%>

If you are using f.select then use this. Notice the empty curly braces. That is because html_options is the fourth argument for f.select helper. Checkout the documentation here.

<%= f.select :barrister_id, options_from_collection_for_select(@barristers,
  :id,:code), {}, id: "barristerselect" %>

Другие советы

This is because you changed the id of select control. Try to change id to mail_barrister_id (default id generated by select_tag helper). Also should change id in the java script of select2

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top