Tasos Anesiadis
Tasos Anesiadis

Reputation: 1150

Rails, "respond_to do |format|" returns ActionController::UnknownFormat

I am trying to run some javascript straight from my controller.

I have already created my JS file in views/articles/create.js.erb

In my articles_controller:

def create
        @article = Article.new(article_params)
        if @article.save && manage_strings
            @status = 'success'
        else
            @status = 'error'
            @errormessages= @article.errors.full_messages
        end
        respond_to do |format|
            format.js
        end

end

When I run my app the respond_to do |format| gives me ActionController::UnknownFormat

I tried updating my mime_types.rb with the following line and restarting my server as suggested somewhere else, but to no results:

Mime::Type.register "application/javascript", :js

The wierd thing is that in my languages_controller the following works perfectly with my js file in views/languages/list.js.erb.

def list
    respond_to do |format|
        format.js
    end
end

Any ideas or suggestions regarding what could be at fault here?

Any help appreciated.

Upvotes: 2

Views: 1926

Answers (2)

max
max

Reputation: 102036

The most likely explanation is that the request is not requesting JS. In order for rails to treat the request as JS the path needs to end with .js or have the correct Accept or Content-Type headers. Not that the mime type is not registered with rails as it registers the most common mime-types for javascript.

  1. Check the rails log to confirm: tail -f logs/development.log
  2. Check the browser console for errors.
  3. Check that form that is has the data-remote="true" attribute.

<%= form_for(@thing, remote: true) %>

Upvotes: 1

uday
uday

Reputation: 8710

Shouldn't your create action be something like this?

def create
  @article = Article.new(article_params)
  respond_to do |format|
    if @article.save && manage_strings
      format.html { redirect_to @article, notice: 'Article was successfully created.' }
      format.json { render :show, status: :created, location: @article }
    else
      format.html { render :new }
      format.json { render json: @article.errors.full_messages, status: :unprocessable_entity }
    end
  end

end

Upvotes: 1

Related Questions