Rails 4.1 ActionController ::使用AngularJS的respond_with的UnknownFormat错误

时间:2014-06-08 12:06:57

标签: ruby-on-rails angularjs ruby-on-rails-4

在rails控制器中尝试使用respond_to和respond_with时,继续获取ActionController:UnknownFormat错误。控制器中以下行出错。

respond_with @surveys 

在/ app / assets / controllers / surveys_controller

respond_to :json

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

在/config/routes.rb

WebInsight::Application.routes.draw do

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

   resources :surveys
end

在/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>

在/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();
}]);

3 个答案:

答案 0 :(得分:3)

它有接触

respond_to :json
当路由将json定义为默认值

时,

有效

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

不允许Controller中的html只是将以下内容添加到方法

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

答案 1 :(得分:2)

/app/assets/controllers/surveys_controller中,您可以将respond_with更改为render json:,如下所示:

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

使用Rails 4.1.5对我有用。

答案 2 :(得分:1)

通过以下修正案解决了这个问题:

在/ app / assets / controllers / surveys_controller中,使用

respond_to :json, :html

而不仅仅是

respond_to :json