簡體   English   中英

Rails 4.1 ActionController ::使用AngularJS的respond_with的UnknownFormat錯誤

[英]Rails 4.1 ActionController::UnknownFormat error for respond_with using AngularJS

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

它有接縫

respond_to :json

路由將json定義為默認值時有效

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

不允許控制器中的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

/app/assets/controllers/surveys_controller您可以更改respond_withrender json:如下所示:

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

這對我來說使用Rails 4.1.5。

解決了以下修正案:

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

respond_to :json, :html

而不僅僅是

respond_to :json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM