title: Creating objects with Mongoid embedded many to one relationships
body: <p>I'm trying to create an object with embedded attributes for testing. This example uses a user with multiple languages but I would love a solution for the general case of creating embedded objects.</p>
  
  <p>Present creation code:</p>
  
  <pre><code>def valid_attributes
    { :languages =&gt; [Language.new(language: "en-US", proficiency: "1")] }
  end
  
  user = User.create! valid_attributes
  </code></pre>
  
  <p>The models:</p>
  
  <pre><code>class User
    include Mongoid::Document
    field :languages
    embeds_many :languages 
    validates_presence_of :languages
    attr_accessible :languages_attributes
    accepts_nested_attributes_for :languages, :reject_if =&gt; lambda { |a| a[:language].blank? }, :allow_destroy =&gt; true
  end
  
  class Language
    include Mongoid::Document
    field :language
    field :proficiency
    key :language
    embedded_in :user
    attr_accessible :language, :proficiency 
  end
  </code></pre>
  
  <p>These models work fine for creating objects from nested forms in Ryan Bates' footsteps (https://github.com/ryanb/complex-form-examples). I don't know whether that is the right way, but I assume so.</p>
  
  <p>There are a few obvious solutions I can see. One is to just hardcode the input like what is generated from the forms:</p>
  
  <pre><code>{"user"=&gt;{ "languages_attributes"=&gt;{"0"=&gt;{"language"=&gt;"en-US", "proficiency"=&gt;"1", "_destroy"=&gt;"false", "id"=&gt;"en-dash-us"}}}
  </code></pre>
  
  <p>That doesn't seem DRY or sane in the long run, to me.</p>
  
  <p>The other solution is to just cut the embedded objects and use Arrays. Mongoid is pretty good at supporting arrays but you lose the ability to write validations for each object and the code would be less reusable.</p>
  
  <p>Thoughts, Stackoverflowers?</p>