User has two addresses shipping(:address_type=0) and billing(:address_type=1) User form with 2 classic nested forms for each address type are generated square times every submit and failed validation.
<强 > 模式: 强 >
class User < ActiveRecord::Base
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses
validates_associated :addresses
end
class Address < ActiveRecord::Base
belongs_to :user
validates :user, :address_type, :first_name, :last_name, :street
end
<强 > 主计长 强 >
class UsersController < ApplicationController
public
def new
@user = User.new
@shipping_address = @user.addresses.build({:address_type => 0})
@billing_address = @user.addresses.build({:address_type => 1})
end
def create
@user = User.new(params[:user])
if @user.save
#fine
else
render => :new
end
end
<强 > 未完成表格 强 >
=form_for @user, :html => { :multipart => true } do |ff|
=ff.fields_for :addresses, @shipping_address do |f|
=f.hidden_field :address_type, :value => 0
=ff.fields_for :addresses, @billing_address do |f|
=f.hidden_field :address_type, :value => 1
=ff.submit