Question

When the page loads, the resource throws a 404 because the $resource is reading nil for :city_id. I am beginning with angularjs so any clarification is appreciated.

The form entries fail to persist because this $resource is also used for PUT'ing the entries in the model.

app = angular.module("CityAngular", ["ngResource"])
app.factory "Seal", ["$resource", ($resource) ->
    $resource("/cities/:city_id/seals/:id", {city_id: "@city_id", id: "@id"}, {update: {method: "PUT"}})
]

@SealCtrl = ["$scope", "Seal", ($scope, Seal) ->
    $scope.seals = Seal.query()

    $scope.addSeal = ->
        seal = Seal.save($scope.newSeal)
        $scope.seals.push(seal)
        $scope.newSeal = {}
]
Was it helpful?

Solution

As you mention rails, I suggest you look at angularjs-rails-resource. It makes working with resources much easier. As you are nesting your seals below city, you always have to supply a city_id.

app = angular.module("CityAngular", [])
app.factory "Seal", ["railsResourceFactory", ($resource) ->
  $resource url: "/cities/{{city_id}}/seals/{{id}}", name: 'seal'
]

app.controller 'SealCtrl', ["$scope", "Seal", ($scope, Seal) ->
  $scope.city_id = 1

  $scope.seals = Seal.query(city_id: $scope.city_id)

  $scope.addSeal = ->
    $scope.newSeal.city_id = $scope.city_id
    seal = new Seal($scope.newSeal).create()
    $scope.seals.push(seal)
    $scope.newSeal = {}
]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top