3

我想映射默认的 AngularJS $resource 操作:

  '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。

4

1 回答 1

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
]
于 2013-03-02T19:05:38.280 回答