Mongoid Embedded Documents embeds_many form example using simple_form

Below is an example of how to produce a form for an embeds_many association for mongoid and simple_form (although this will also work with the standard rails helpers).

Class User
  include Mongoid::Document
  embeds_many :children, :class_name => "Child"
  accepts_nested_attributes_for  :children, reject_if: proc { |attributes| attributes["age"].blank? }
end

Class Children
  include Mongoid::Document
  field :age, type: String
  embedded_in :user
  validates_presence_of :age
end

And on the view side then we can simply use simple_fields_for now as it is a now a nested attribute:

= f.simple_fields_for :children do |child_form|
  = child_form.input :age

You can now have as many children as you want and the form will pass the correct params back.

No Comments

RSS feed for comments on this post.

No comments yet.

Leave a comment

Preview: