我想通过使用Angular.js和Rails来显示卡片的索引。
这是我的代码。
# app/views/decks/show.html.erb
<div ng-controller="DeckCtrl">
<form ng-submit="addCard()">
<input type="text" ng-model="newCard.front" />
<input type="submit" value="Add">
</form>
{{newCard.front}}
<ul>
<li ng-repeat="card in cards">
{{card.front}}
</li>
</ul>
</div>
咖啡脚本
# app/assets/javascripts/decks.js.coffee
app = angular.module("Deck", ["ngResource"])
@DeckCtrl = ($scope, $resource) ->
Card = $resource("/cards/:id", {id: "@id"}, {update: {method: "PUT"}})
$scope.cards = Card.query()
$scope.addCard = ->
$scope.cards.push($scope.newCard)
$scope.newCard = {}
CardsController
。
class CardsController < ApplicationController
respond_to :json
def index
respond_with Card.all
end
def show
respond_with Card.find(params[:id])
end
def create
respond_with Card.create(card_params)
end
def update
respond_with Card.update(params[:id], card_params)
end
def destroy
respond_with_Card.destroy(params[:id])
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def card_params
params.require(:card).permit(:front, :back, :tips, :cardtype, :deck_id, :box_number)
end
end
addCard
功能正常,但Card.query()
给了我这个错误。
Started GET "/cards" for 127.0.0.1 at 2014-04-17 10:39:42 +0900
Processing by CardsController#index as HTML
Completed 406 Not Acceptable in 2ms
ActionController::UnknownFormat - ActionController::UnknownFormat:
看起来Angular.js
发送HTML
而非json
,导致错误,是吗?
如何删除此错误?
答案 0 :(得分:2)
406表示服务器不支持客户端请求的格式。
angular发送的默认Accept
标头为application/json, text/plain, */*
。所以基本上它接受一切。只要我能看到它,$resource
就不会改变任何东西。
有可能在您的应用程序中的某个位置设置了您的服务器无法处理的格式。
答案 1 :(得分:1)
试试这个?
$resource("/cards/:id", {id: "@id"}, {update: {method: "PUT", responseType: 'json'}})