Created
March 7, 2012 19:24
-
-
Save gagnedan/1995293 to your computer and use it in GitHub Desktop.
Nested Form in Rails 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# controller | |
def new | |
@account = Account.new | |
@account.build_user # build a blank user or the child form won't display | |
@account.build_company # build a blank company or the child form won't display | |
end | |
# model | |
belongs_to :user, :foreign_key => "account_holder_id" | |
belongs_to :company, :foreign_key => "primary_company_id" | |
accepts_nested_attributes_for :user, :company | |
# Setup accessible (or protected) attributes for your model | |
attr_accessible :name, :user_attributes, :company_attributes | |
# view | |
<%= form_for [@account] do |f| %> | |
<%= f.fields_for :company do |company_form| %> | |
<div class="field"><%= company_form.label :name %><br /> | |
<%= company_form.text_field :name, :class => "formfield"%></div> | |
<% end %> | |
<%= f.fields_for :user do |user_form| %> | |
<div class="field"><%= user_form.label :first_name %><br /> | |
<%= user_form.text_field :first_name, :class => "formfield"%></div> | |
<div class="field"><%= user_form.label :last_name %><br /> | |
<%= user_form.text_field :last_name, :class => "formfield"%></div> | |
<div class="field"><%= user_form.label :email %><br /> | |
<%= user_form.email_field :email, :class => "formfield"%></div> | |
<% end %> | |
<%= f.submit %> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment