Search code examples
ruby-on-railsangularjsruby-on-rails-4angularjs-serviceangular-resource

Angularjs Rails Resource save() function not working from controller


I am using angularjs-rails-resource , in my Rails Angular App.

Account Resources

myApp.factory('Account', ['railsResourceFactory','railsSerializer', function                          
  (railsResourceFactory,railsSerializer) {
    return railsResourceFactory({
     url: '/accounts',
     name: 'account',
     serializer: railsSerializer(function () {
       this.nestedAttribute('address');
    })
  });
}]);

UserController.js

function userController($scope,$location,Auth,$rootScope,$http,Useraccount,Account) {
  $scope.profileUpdate = function() {

   //Useraccount.save(); // THIS WORKS

   $scope.account = {}
   $scope.account.save()  // Throwing error : undefined function save
 }
}

UserAccount Service

myApp.service('Useraccount',function(Auth,$location,$rootScope,Account){
 var account;
 var query = function(){
 var promise = Account.query().then(function (results) {
   account = results;
 }, function (error) {
   alert("Went Wrong while fetching User Account!!")
 });

 return promise;
}

var save = function() {
  account.save().then(function (results) {
   console.log(results);
  }, function (error) {
    alert("Went Wrong!!")
  });
 }
return {
   query:query,
   save:save
  }
 })
});

I am not sure why the save function from UserController is not working though I have imported Account resources as dependency. I did same in service , but it was working there. Any clue will be helpful.


Solution

  • You are actually calling the save() method for an empty javascript object. I don't see the point here.

    Anyway you need an Angular object to do so. So either load account data from server.

    $scope.accounts = Account.query(); // Will be an Array of accounts
    

    Or create new instance of Account

    $scope.account = new Account(); // An empty object