[英]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. 尝试在rails控制器中使用respond_to和respond_with时,继续获取ActionController:UnknownFormat错误。 Error on the following line in controller.
控制器中以下行出错。
respond_with @surveys
In /app/assets/controllers/surveys_controller 在/ app / assets / controllers / surveys_controller中
respond_to :json
def index
@surveys = Survey.all
respond_with @surveys
end
In /config/routes.rb 在/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 在/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/assets/javascripts/angular/controllers/surveys_ctrl.js中
app.controller('SurveysCtrl', ['$scope', '$resource', function($scope, $resource) {
var Surveys = $resource('/api/surveys');
$scope.surveys = Surveys.query();
}]);
it seams that having 它有接缝
respond_to :json
is valid when the routes defines json as the default 路由将json定义为默认值时有效
scope :api, defaults: {format: :json} do
resources :resources
end
to not allow the html in the Controller simply add the following to the method 不允许控制器中的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
In /app/assets/controllers/surveys_controller
you could change respond_with
to render json:
like so: 在
/app/assets/controllers/surveys_controller
您可以更改respond_with
以render json:
如下所示:
def index
@surveys = Survey.all
render json: @surveys
end
That worked for me using Rails 4.1.5. 这对我来说使用Rails 4.1.5。
Solved it with the following amendment: 解决了以下修正案:
In /app/assets/controllers/surveys_controller, use 在/ app / assets / controllers / surveys_controller中,使用
respond_to :json, :html
instead of just 而不仅仅是
respond_to :json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.