Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

field_for and nested form with mongoid

Could somebody give me the working example of nested form using mongoid?

My models:

class Employee 
  include Mongoid::Document 
  field :first_name 
  field :last_name 
  embeds_one :address 
end

class Address 
  include Mongoid::Document 
  field :street 
  field :city 
  field :state 
  field :post_code 
  embedded_in :employee, :inverse_of => :address 
end
like image 409
Kir Avatar asked Feb 22 '11 13:02

Kir


1 Answers

Your models:

class Employee 
  include Mongoid::Document 

  field :first_name 
  field :last_name 
  embeds_one :address
  # validate embedded document with parent document
  validates_associated :address
  # allows you to give f.e. Employee.new a nested hash with attributes for
  # the embedded address object
  # Employee.new({ :first_name => "First Name", :address => { :street => "Street" } })
  accepts_nested_attributes_for :address
end

class Address 
  include Mongoid::Document 

  field :street 
  field :city 
  field :state 
  field :post_code 
  embedded_in :employee, :inverse_of => :address 
end

Your controller:

class EmployeesController < ApplicationController

  def new
    @employee = Employee.new
    # pre-build address for nested form builder
    @employee.build_address
  end

  def create
    # this will also build the embedded address object 
    # with the nested address parameters
    @employee = Employee.new params[:employee]

    if @employee.save
      # [..]
    end
  end      

end

Your template:

# new.html.erb
<%= form_for @employee do |f| %>
  <!-- [..] -->
  <%= f.fields_for :address  do |builder| %>
     <table>
       <tr>
         <td><%= builder.label :street %></td>
         <td><%= builder.text_field :street %></td>
       </tr>
       <!-- [..] -->
     </table>
  <% end %>
<% end %>

That should work for you!

Julian

like image 179
Julian Maicher Avatar answered Nov 13 '22 11:11

Julian Maicher