, , .
:
class Business < ActiveRecord::Base
has_one :mailing_address, :class_name => "Address", :dependent => :destroy
accepts_nested_attributes_for :mailing_address
has_many :locations
accepts_nested_attributes_for :locations
end
class Location < ActiveRecord::Base
has_one :address, :dependent => :destroy
accepts_nested_attributes_for :address
belongs_to :business
end
class Address < ActiveRecord::Base
belongs_to :business
belongs_to :location
end
:
def new
@business = Business.new
mailing_address = @business.build_mailing_address
3.times do
location = @business.locations.build
address = location.build_address
end
respond_to do |format|
format.html
format.xml { render :xml => @business }
end
end
, :
#app/views/businesses/_form.html.erb
<%= form_for(@business) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<%= f.fields_for :mailing_address do |builder| %>
<h3>Mailing Address</h3>
<%= render "address_fields", :f => builder %>
<% end %>
<%= f.fields_for :locations do |builder| %>
<h3>Location</h3>
<%= render "locations_fields", :f => builder %>
<%= builder.fields_for :address do |mini_builder| %>
<h3>Location Address</h3>
<%= render "address_fields", :f => mini_builder %>
<% end%>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
:
<p>
<%= f.label "Street Address"%>
<%= f.text_field :street %>
<%= f.label "City"%>
<%= f.text_field :city %>
<%= f.label "State"%>
<%= f.text_field :state %>
<%= f.label "Zip"%>
<%= f.text_field :zip %>
</p>
:
<p>
<%= f.label "Location Name"%>
<%= f.text_field :name%>
</p>
. , has_one has_many - . , .
- , , -, - :
def possible_mailing_addresses
Location.where(:business_id=>self.id).joins(:address)
end