0

I'm trying to create a form, where I can upload an CSV file to import or to preview before import it.

In my form I have:

<%= form_for(@contact_import, :remote => true) do |f| %>
  <% if @contact_import.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@contact_import.errors.count, "error") %> prohibited this import from completing:</h2>
      <ul>
      <% @contact_import.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.file_field :file %>
  </div>
  <%= f.submit "Import" %>
  <%= f.submit "Preview", :name => 'preview' %>

and in my controller:

  def create
    @contact_import = ContactImport.new(params[:contact_import])

    if params[:preview]
      logger.debug "Let's preview the contacts:" + params.inspect
      @contacts = @contact_import.update_preview
      @contact_attributes = ContactImport.mapping_attributes
      #I should now update the preview div
    else
      logger.debug("Got the commit" + params.inspect)
      if @contact_import.save
        redirect_to root_url, notice: "Imported contacts successfully."
      else
        render :new
      end
    end
  end

How can I update the view to show the preview contacts, by uploading the CSV file?

Note: The CVS file processing at the moment is at the model and had been omitted.

Paulo Fidalgo
  • 21,709
  • 7
  • 99
  • 115

1 Answers1

2

I'd take them to another version of the new page, parse the file and fill the contact_import object - prepare the page with hidden variables to be submitted to the create page.

You can simply look for this button push and render the preview page, using the generated @contact_import generated from the file

  def create
    @contact_import = ContactImport.new(params[:contact_import])

    if params[:preview]
      render :preview 
    elsif @contact_import.save
      redirect_to root_url, notice: "Imported contacts successfully."
    else
      render :new
    end
  end

preview.html.erb is similar to new.html.erb, but with hidden inputs and back button. Posting from preview will also go to create, but should not cause any error conditions.

I don't believe you'll need a new route - just render :preview instead of :new in this case.

Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70
  • I believe he's making a remote form call, render alone won't work in this case. – Noz May 23 '13 at 22:48
  • 1
    Sorry - I didn't notice that when I posted. If you're going to do a remote form with a file field, there's a lot more to it. You might want to look at a gem like https://github.com/JangoSteve/remotipart. Though, I can't be sure it works with rails 3.2 – Mark Swardstrom May 23 '13 at 23:50