Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.1 ActionController::UnknownFormat error for respond_with using AngularJS

Keep getting ActionController:UnknownFormat error when trying to use respond_to and respond_with in rails controller. Error on the following line in controller.

respond_with @surveys 

In /app/assets/controllers/surveys_controller

respond_to :json

def index
  @surveys = Survey.all
  respond_with @surveys
end

In /config/routes.rb

WebInsight::Application.routes.draw do

   scope :api do
      resources :surveys, defaults: {format: 'json'}
   end

   resources :surveys
end

In /app/assets/views/surveys/index.html.erb

<h1>Your Surveys</h1>

<form>
  <input type="text" ng-model='newSurvey' placeholder="Enter a survey">
  <input type="submit" value="Add">
</form>

<div ng-controller="SurveysCtrl">
    <ul>
        <li ng-repeat="survey in surveys">
          {{ survey.theme_id }}, {{ survey.name }}, {{ survey.description }}
        </li>
    </ul>
</div>

In /app/assets/javascripts/angular/controllers/surveys_ctrl.js

app.controller('SurveysCtrl', ['$scope', '$resource', function($scope, $resource) {
   var Surveys = $resource('/api/surveys');
   $scope.surveys = Surveys.query();
}]);
like image 309
CS Koh Avatar asked Jun 08 '14 12:06

CS Koh


3 Answers

it seams that having

respond_to :json

is valid when the routes defines json as the default

scope :api, defaults: {format: :json} do
  resources :resources
end

to not allow the html in the Controller simply add the following to the method

def new
  @resource = Resource.new
  respond_with(@resource) do |format|
    format.html { render nothing: true, status: :unauthorized }
    format.json { render :json => @resource.as_json }
  end
end
like image 142
Baz Avatar answered Nov 05 '22 10:11

Baz


In /app/assets/controllers/surveys_controller you could change respond_with to render json: like so:

def index
  @surveys = Survey.all
  render json: @surveys
end

That worked for me using Rails 4.1.5.

like image 28
RKelley Avatar answered Nov 05 '22 10:11

RKelley


Solved it with the following amendment:

In /app/assets/controllers/surveys_controller, use

respond_to :json, :html

instead of just

respond_to :json
like image 1
CS Koh Avatar answered Nov 05 '22 10:11

CS Koh