用户有两个地址 shipping(:address_type=0) 和 billing(:address_type=1) 每次提交和验证失败时,都会生成每个地址类型的 2 个经典嵌套表单的用户表单。
楷模:
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