Rails3 fails validation and loses child fields

I have a form that prompts for a job and job_files to attach. When the job save fails due to validation, the selected job_files disappear when the form redisplays. How do I retain the child fields? All parent fields are retained in the form but the child fields are gone.

job model:

class Job < ActiveRecord::Base
  has_many :job_files, :dependent => :destroy
  accepts_nested_attributes_for :job_files, :allow_destroy => true
  validates_acceptance_of :disclaimer, :allow_nil => false, :accept => true, :on => :create, :message=>'Must accept Terms of Service'

end

job_files model:

class JobFile < ActiveRecord::Base
  belongs_to :job
  has_attached_file :file
end

jobs_controller:

def new
    @upload_type = UploadType.find_by_id(params[:upload_job_id])
    @job = Job.new
    @job.startdate = Time.now
    10.times [email protected]_files.build}
    @global_settings = GlobalSettings.all
  end

  def create
    @global_settings = GlobalSettings.all
    if params[:cancel_button]
      redirect_to root_path
    else
      @job = Job.new(params[:job])
      @job.user_id = current_user.id
      @upload_type = UploadType.find_by_id(@job.upload_type_id)
      if @job.save
        JobMailer.job_uploaded_notification(@upload_type,@job).deliver
        flash[:notice] = "Job Created"
        redirect_to root_path
      else
        # retain selected files if save fails
        (10 - @job.job_files.size).times { @job.job_files.build }
        flash[:error] = "Job Creation Failed"
        render :action => :new
      end
    end    
  end

job_files partial within job form:

<%= form.fields_for :job_files, :html=>{ :multipart => true } do |f| %>
   <li class="files_to_upload">
      <%= f.file_field :file %>
   </li>
<% end %>

Any help would be appreciated since I can not find any solution online.

That's standard-issue behavior. Really, the only way to workaround it would be to persist the files first, regardless of whether validation passes. Then, run your validations. But that's definitely a workaround.

You could also do client-side validations before the server-side ones; that way, you'd have better assurances that the user's data is valid BEFORE they submit to the server, such that they won't encounter any server-side validation failures, and the files will always make it. I'd probably go that route if I were in your shoes. Note that client-side validation is NOT a replacement for server-side validation, just will help your users in this case.

Hope that helps!

What Others Are Reading