So I am seeing some very strange functionality in my app. I have a pretty complex form with nested attributes. Basically on a failed validation I am returned to the form and the failed record has been duplicated. It seems it may be something having the way a model initializes a record after it has failed validation.
NOTE: I am using formtastic to build the form but I have ruled it out as the culprit.
My model is pretty complex, but the parts that matter are:
...
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
A Basic Controller:
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
And the view:
.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"
The reason that this is happening is that you have User.new in both your model and the “new” action of your controller, I would do the initialization in one place. I do it in the “new” action.