0

I'm following the jquery file upload video from RailsCast but I can't get the images to show up without refreshing the page.

My photo is being uploaded through this form:

<%= simple_form_for @upload, html: { multipart: true, id: 'add_new_project_photos' } do |f| %>
  <%= f.simple_fields_for :project_images, ProjectImage.new, child_index: ProjectImage.new.object_id do |ff| %>
    <%= ff.file_field :photo, multiple: true, name: "project[project_images_attributes][][photo]" %>
  <% end %>
<% end %>

I also created a create.js.erb file.

<% if @project.project_images.new_record? %>
    alert("Failed to upload painting: <%= j @painting.errors.full_messages.join', ').html_safe %>");
<% else %>
  $("#added_photos").append("<%= j render(@project) %>");
<% end %>

My controller

class ProjectsController < ApplicationController

  #... other methods

  def create
    @project = Project.new(trip_params)
    @upload = Project.create(trip_params)

    if request.xhr?
      redirect_to root_url
    else
      redirect_to :back
    end

    respond_to do |format|
      if @project.save

        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

end

My coffee script file

jQuery ->
    $('#add_new_trip_photos').fileupload
    dataType: "script"

1 Answer 1

0

You need to respond to js as well. In your create method you are only responding to html and json

format.js

Should be placed inside your respond_to block

10
  • added that after format.json { render :show, status: :created, location: @project }, but didn't work.
    – hellomello
    Aug 16, 2015 at 16:29
  • I would look in the developer tools in your browser and make sure you are getting the JS as a response first before you change things. Also, if you put your format.js inside the if save condition, you will not see an error if one arises. I would take it out of your if-else, since you are handling the error in your create.js
    – aaron.v
    Aug 16, 2015 at 16:38
  • When I tried to upload something, I get a POST method with a 302 status and text/html type and also a GET method with a 200 status and xhr type.
    – hellomello
    Aug 16, 2015 at 16:51
  • @hellomello In addition to adding format.js, you'll need to add remote: true to the form to make this an ajax form.
    – Fan Jin
    Aug 16, 2015 at 16:52
  • 1
    Let us continue this discussion in chat.
    – hellomello
    Aug 16, 2015 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.