Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top