Emily Hoang
Emily Hoang

Reputation: 1

PostController#index is missing a template

I'm trying to build Instagram on Rails and ran into this super long error. I'm pretty lost where to look for the problem. It's complaining that I don't have a template for the index action which I actually do.

My guess is because I use Dropzone to reload the page. Here is the code:

Dropzone.autoDiscover = false;

$(document).ready(function(){
  $(".upload-images").dropzone({
    addRemoveLinks: true,
    maxFilesize: 1,
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    maxFiles: 100,
    paramName: "images",
    previewsContainer: ".dropzone-previews",
    clickable: ".upload-photos-icon",
    thumbnailWidth: 100,
    thumbnailHeight: 100,

    init: function(){
      var myDropzone = this;

      this.element.querySelector("input[type=submit]").addEventListener("click", function(e){
        e.preventDefault();
        e.stopPropagation();
        myDropzone.processQueue();
      });

      this.on("successmutiple", function(files, response){
        window.location.reload();
      })

      this.on("errormultiple", function(files, response){
        toastr.error(response);
      });
    }
  })
});

I can't post images because of this long error. Could someone please explain what it's saying? and what I should do to fix the problem?

ActionController::UnknownFormat in PostsController#index PostsController#index is missing a template for this request format and variant. request.formats: ["application/json"] request.variant.....

Upvotes: 0

Views: 474

Answers (1)

Jonathan Bennett
Jonathan Bennett

Reputation: 1065

When Rails response to a request, by convention it will hit the controller action and then render a template at the path app/views/PLURAL_RESOURCE_NAME/ACTION.REQUEST_FORMAT.erb. For example when requesting the html for the posts index path this is app/views/posts/index.html.erb. You are also going to need to also create a file at app/views/posts/index.json.erb which will be rendered when Dropzone is hitting the endpoint.

If you need to do different work depending on the format of the request, you can also do different logic in the controller:

class PostsController < ApplicationController

    def index
        @posts = Post.all # this is available to all formats

        respond_to do |format|
            format.html # just do the default stuff, ie. render index template
            format.json { # do other stuff just for the json version
                @foo = "bar"
                do_stuff()
            }
        end
    end

end

You can also do render json: @posts if you just want to dump the data without creating a template. Be careful that you want to expose all that data though. For example if you were doing this with users, you would have password hashes and email address being exposed.

Upvotes: 3

Related Questions