所以我在我的應用程序中看到了一些非常奇怪的功能。我有一個非常複雜的嵌套屬性表單。基本上,驗證失敗後,我將返回到表單,失敗的記錄已被複制。看起來它可能是模型在驗證失敗後初始化記錄的方式。從具有嵌套屬性的表單驗證失敗時的重複記錄
注意:我使用formtastic來構建表單,但我排除了作爲罪魁禍首。
我的模型是相當複雜的,但重要的部分是:
...
accepts_nested_attributes_for :users
...
after_initialize :build_structure
...
private
def build_structure
# builds the first user when the firm is initialized
if users.length < 1
logger.debug "First User!!!"
user = users.new
contact = user.contact = Contact.new
contact.email_addresses.new
end
end
一個基本的控制器:
def new
@firm = Firm.new
render "new", layout: "blankslate" # new.html.erb
end
def create
@firm = Firm.new(params[:firm])
respond_to do |format|
if @firm.save
format.html { redirect_to root_url(subdomain: @firm.url)}
else
format.html { render action: "new", layout: "blankslate" }
end
end
end
和視圖:
.container
.row
.span4.offset4.well
.page-header
%h1 Create Your Firm
= semantic_form_for @firm, url: signup_path do |f|
= f.input :name
= f.input :url
.page-header
%h1 Create Your User
= f.fields_for :users do |u|
= u.fields_for :contact do |c|
= c.input :first_name
= c.input :last_name
= c.fields_for :email_addresses do |cf|
= cf.input :value, label: "Email Address"
= u.input :password
= u.input :password_confirmation
= f.submit "Signup", class: "btn btn-primary"
做到了這一點,並增加了一些額外的魔力,以確保我沒有得到任何額外的記錄一代。 – 2012-03-09 17:04:54