2014-06-08 18 views
6

Tiếp tục nhận ActionController: Lỗi UnknownFormat khi cố gắng sử dụng response_to và respond_with trong bộ điều khiển đường ray. Lỗi trên dòng sau trong bộ điều khiển.Rails 4.1 ActionController :: UnknownFormat error for respond_with sử dụng AngularJS

respond_with @surveys 

Trong/app/tài sản/controllers/surveys_controller

respond_to :json 

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

Trong /config/routes.rb

WebInsight::Application.routes.draw do 

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

    resources :surveys 
end 

Trong /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/javascri pts/góc/controllers/surveys_ctrl.js

app.controller('SurveysCtrl', ['$scope', '$resource', function($scope, $resource) { 
    var Surveys = $resource('/api/surveys'); 
    $scope.surveys = Surveys.query(); 
}]); 

Trả lời

1

Giải quyết nó với việc sửa đổi như sau:

Trong/app/tài sản/controllers/surveys_controller, sử dụng

respond_to :json, :html 

thay vì chỉ

respond_to :json 
+1

Một lời cảnh cáo ở đây: Nếu bạn đặt respond_to: json,: html, có nghĩa là đường ray sẽ tiếp tục phân phối đầu ra HTML bằng cách sử dụng đường ray chứ không phải góc cạnh. Nếu bạn muốn AngularJS phục vụ tất cả nội dung HTML như front-end, trong khi đường ray chỉ xử lý back-end (như trường hợp cho 1 ứng dụng trang), bạn không nên bật 'respond_to: html'. Thay vào đó, hãy đọc về định tuyến AngularJS. [http://scotch.io/tutorials/javascript/single-page-apps-with-angularjs-routing-and-templating] –

2

đường nối có

respond_to :json 

là hợp lệ khi các tuyến đường xác định json như là mặc định

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

không cho phép html trong điều khiển đơn giản là thêm dòng sau vào phương pháp

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 
+0

Bạn có thể thêm các chi tiết khác về giải pháp bạn cung cấp không? – abarisone

+0

Xin chào, muốn tăng đại diện của bạn lên 1000% –

2

Trong /app/assets/controllers/surveys_controller bạn có thể thay đổi respond_with đến render json: như vậy:

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

Điều đó làm việc cho tôi bằng cách sử dụng Rails 4.1.5.

Các vấn đề liên quan