1

I'm following the example from mightygio (http://mightygio.com/2013/05/integrating-rails-and-angularjs-part-3-rest-and-angular-resource) and would like to simplify the postData when updating.

Currently I have this

  $scope.update = ->
    Letter.update
      id: $stateParams['id']
    ,
      letter:
        subject: $scope.letter.subject
        body: $scope.letter.body

    # success
    , (response) ->
      $location.path "/letters"

    # failure
    , (response) ->

When I have a large form with lots of data this gets rather long and hard to maintain. It would be nicer if I could just pass the $scope.letter like so:

  $scope.update = ->
    Letter.update
      id: $stateParams['id']
    ,
      letter: $scope.letter

    # success
    , (response) ->
      $location.path "/letters"

    # failure
    , (response) ->

The problem I have is I cannot pass certain attributes to my backend when updating these are created_at, id & updated_at keys.

How could I remove these keys before sending my JSON to the server?

UPDATE

I suppose I could use something like this, but is there a better way?

  $scope.update = ->
    letter = {}
    #  Strip out id, created_at & updated_at
    angular.forEach($scope.letter, (value,key) ->
      if(key!='id' && key!='created_at' && key!='updated_at')
        letter[key]=value
    ,letter)

    Letter.update
      id: $stateParams['id']
    ,
      letter: letter
    # success
    , (response) ->
      $location.path "/letters"

    # failure
    , (response) ->

1 Answer 1

0
+50

Highly recommend to use well known and performant utility libraries like Lo-Dash or Underscore. Using either of these you can easily choose to either include a whitelist of keys, or exclude a list of blacklisted keys.

Whitelist example:

_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}

Blacklist example:

_.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');
=> {name: 'moe', age: 50}

PS If you use the well known Restangular library the decision becomes even easier, as it depends on Lodash (or Underscore) already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.