简体   繁体   中英

ActionController::UnknownFormat error with Ajax request in Rails 6.0.1

I've found many similar questions, but none that have been able to fix my error so far.

In my recipes.show.html.haml file I have

= simple_form_for @recipe, url: upload_photo_recipe_url, remote: true do |f|
  = f.file_field :photo, id: 'photo-uploader', class: 'd-none'
  = f.submit id: 'submit-photo', class: 'd-none'

This is submitted in my show.js file with

$('#photo-uploader').change(function() {
  $(`#edit_recipe_${recipeId}`).submit()
})

What I want is to then display this photo once it finishes uploading without refreshing the page, so in recipes_controller.rb have

def upload_photo
  @recipe = Recipe.find(params[:id])
  if @recipe.update(recipe_params)
    respond_to do |format|
      format.js
    end
  else

  end
end

The intended behaviour is to then run the upload_photo.js.erb file (currently only contains a console.log), but it never gets there.

As soon as the photo finishes uploading, I get an error page: 'ActionController::UnknownFormat in RecipesController#upload_photo', highlighting the 'respond_to do |format|' line.

What is going wrong that I cannot display reach the upload_photo.js.erb file?

Clicking through the error, I get a No route matches [GET] "/recipes/11/upload_photo" error.

Any help would be really appreciated. I've been trying to fix this for a couple of days now.

Thanks for reading!

The problem was with the middle line in my show.js function:

$('#photo-uploader').change(function() {
  $(`#edit_recipe_${recipeId}`).submit()
})

By updating my show.js to 'click' the form instead, as in

$('#photo-uploader').change(function() {
  $('#submit-photo').click()
})

I got through to my upload_photo.js.erb file once the photo uploaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM