Created
January 13, 2010 23:09
-
-
Save lancejpollard/276659 to your computer and use it in GitHub Desktop.
Rails Nested Forms with belongs_to, doesn't work by default
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
# user.rb | |
class User < ActiveRecord::Base | |
belongs_to :address | |
accepts_nested_attributes_for :address # can't have allow_destroy | |
end | |
# users_controller.rb | |
class UsersController < ApplicationController | |
resource_controller | |
before_filter :load_object, :except => :index | |
# called at the beginning of each action | |
def load_object | |
@user = User.find(...) | |
@user.address ||= Address.new() | |
@user | |
end | |
end | |
# users/edit.html.erb | |
<% form_for(@user, :url => collection_url) do |f| %> | |
<%= render :partial => "form", :locals => { :f => f } %> | |
<p> | |
<%= submit_tag t("create"), {"class" => "wymupdate"}%> | |
</p> | |
<% end %> | |
# users/_form.html.erb | |
<table class="admin-report" width="545"> | |
<fieldset id='name'> | |
<div class="inner"> | |
<p class="field"> </p> | |
<p id="aname" class="field"> | |
<%= f.label :name, t(:name) %><br /> | |
<%= f.text_field :name, :class => 'required' -%><span class="req">*</span> | |
</p> | |
</div> | |
</fieldset> | |
<%= render :partial => "address_form", :locals => { :f => f } %> | |
</table> | |
# users/_address_form.html.erb | |
<fieldset id='address'> | |
<% f.fields_for :address do |address_form| %> | |
<legend><%= t("address")%></legend> | |
<div class="inner"> | |
<p class="field"> </p> | |
<p id="afname" class="field"> | |
<%= address_form.label :firstname, t(:first_name) %><br /> | |
<%= address_form.text_field :firstname, :class => 'required' -%><span class="req">*</span> | |
</p> | |
</div> | |
<% end %> | |
</fieldset> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment