Return to Snippet

Revision: 22512
at January 13, 2010 18:03 by viatropos


Initial Code
# 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">&nbsp;</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">&nbsp;</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>

Initial URL
rails-accepts-nested-attributes-for-belongs-to

Initial Description
Easy way to add belongs_to association to nested forms in Rails

Initial Title
Rails Nested Forms with belongs_to

Initial Tags
rails

Initial Language
Ruby