我想映射默认的AngularJS $资源操作:
'get': {method:'GET'}
'save': {method:'POST'}
'query': {method:'GET', isArray:true}
'remove': {method:'DELETE'}
'delete': {method:'DELETE'}
到这5个Rails RESTful路由:
'show': {method:'GET'} -> get
'create': {method:'POST'} -> save
'update': {method:'PUT'} -> save
'index': {method:'GET', isArray:true} -> query
'delete': {method:'DELETE'} -> remove or delete
除了save
之外,一切都很好。它作为create
请求在POST
上运行。但是当我保存具有PUT
id != null
请求
# This factory needs a smarter $save() method
myServices.factory 'Message', ['$resource', ($resource) ->
Message = $resource "api/users/:user_id/messages/:id",
user_id: '@user_id'
id: '@id'
,
# update should not be needed
update:
method: 'PUT'
Message
]
myApp.controller "UsersShowCtrl", ["$scope", "$routeParams", "User", "Message", ($scope, $routeParams, User, Message) ->
$scope.user = User.get({id: $routeParams.user_id})
$scope.myMessage = new Message {user_id: $routeParams.user_id}
$scope.submitMyMessage = ->
# This should just be:
# $scope.myMessage.$save()
# rather than:
unless $scope.myMessage.id?
$scope.myMessage.$save()
else
$scope.myMessage.$update()
]
我最终还想修改提交的参数,以便我可以将它们命名为默认的rails嵌套参数,即params[:message]
,而不是将它们直接附加到根params
字符串,但首先我需要知道如何最好地修改$ resource。
答案 0 :(得分:1)
在我的脑海中,这个save()方法怎么样?
myServices.factory 'Message', ['$resource', ($resource) ->
Message = $resource "api/users/:user_id/messages/:id",
user_id: '@user_id'
id: '@id'
,
# update should not be needed
update:
method: 'PUT'
Message::save = ->
if @id?
@update()
else
@create()
Message
]