Note that there are some explanatory texts on larger screens.

plurals
  1. POForms to create and update Mongoid array fields
    primarykey
    data
    text
    <p>I've been struggling to create a form for a Mongoid model that has an array field. I want my form to have on text box per entry in the array. If I'm creating a new record, the default will be one empty field (and some javascript to add new fields dynamically on the page).</p> <p>I've searched around for a solution using fields_for but it seems that is more intended to handle the case where you have an array of objects/models and not the case I have, which is an array of strings. </p> <p>I'm going to use the example of a person and a phone number. </p> <pre><code>class Person include Mongoid::Document field :name, :type =&gt; String field :phone_numbers, :type =&gt; Array end </code></pre> <p>For the controller, just assume the typical controller but in the <code>new</code> method I initialized the phone_number array with one blank string.</p> <p>Here's the form code:</p> <pre><code> &lt;%= form_for(@person) do |f| %&gt; &lt;div class="field"&gt; &lt;%= f.label :name %&gt;&lt;br /&gt; &lt;%= f.text_field :name %&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;%= f.label :phone_numbers %&gt;&lt;br /&gt; &lt;% @person.phone_numbers.each do |phone_number| %&gt; &lt;%= text_field_tag "person[phone_numbers][]", phone_number %&gt; &lt;% end %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>This all works fine. There are a few things that I don't like. </p> <ul> <li>The hardcoded name of the field in the text_field_tag call.</li> <li>Using text_field_tag instead of f.text_field</li> <li>Having the feeling like I should somehow be using fields_for instead of this</li> </ul> <p>Does anybody have any better suggestions on how to implement this? Or would you consider this correct?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload