Rails 4.1 ActionController :: UnknownFormat error for response_with using AngularJS

Continue to get ActionController: UnknownFormat while trying to use response_to and reply_with in the rails controller. Error in the next line in the controller.

respond_with @surveys 

In / app / assets / controllers / survey_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(); }]); 
+6
source share
3 answers

he throws that

 respond_to :json 

valid when routes define json as default

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

to prevent html in the controller just add to the method

following:
 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 
+2
source

In /app/assets/controllers/surveys_controller you can change respond_with to render json: as follows:

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

This worked for me using Rails 4.1.5.

+2
source

I solved it with the following amendment:

In / app / assets / controller / survey_controller use

 respond_to :json, :html 

instead

 respond_to :json 
+1
source

Source: https://habr.com/ru/post/970532/


All Articles