Post and Put with Restangular for api Ruby on Rails

1

I'm creating a single page application using angularjs using a ruby on rails API and the restangular to make my requests.

Problem:

The API by default expects POST and PUT requests to arrive in a property with the model name, eg:

user: {name: 'teste', phone: '000000'}, outros_parametros: '';

Meanwhile, the restangular performs these requests by passing the dropped parameters, eg:

name: 'teste', phone: '000000', outros_parametros: '';

resulting in API error: param is missing or the value is empty: user

POST

In POST I managed to solve the problem I believe not in the best way, placing the object inside another with the name of the model as follows:

Does not Work:

$scope.current_user = {name: 'teste', phone: '000000'};
Restangular.all('users').post($scope.current_user);

It works:

$scope.current_user = {name: 'teste', phone: '000000'};
Restangular.all('users').post(user: {$scope.current_user});

PUT

On the PUT, the restangular requests based on the object instance as follows:

# GET
$scope.current_user = Restangular.all('users').get(1).$object;
$scope.current_user.name = 'teste2';

# PUT
$scope.current_user.save();

and in this case I could not get around the problem.

If someone has a solution for PUT and a better solution for POST, I appreciate it.

    
asked by anonymous 14.10.2015 / 16:15

1 answer

1

The solution is to use customPUT . Here's how I describe accessing my API through a factory using ES6:

const ApiFactory = (Restangular) => {
  'ngInject';

  return Restangular.withConfig((RestangularConfigurer) => {
    RestangularConfigurer.setPlainByDefault(true);
    RestangularConfigurer.setBaseUrl(process.env.API_URL);
  });
};

export default ApiFactory;
  

process.env.API_URL comes from the Webpack configuration, it can be a static value.

For ease of access to the Rails resource I use service of Restangular. Here's how to set up a complete resource:

const DisputeFactory = (Api) => {
  'ngInject';

  let dispute = Api.service('disputes');

  return {
    page: () => dispute.getList(),
    get: (id) => dispute.one(id).get(),
    create: (item) => dispute.post({dispute: item}),
    update: (item) => dispute.customPUT({dispute: item}, item.id),
    delete: (id) => dispute.one(id).remove()
  };
};

export default DisputeFactory;

In this way you can inject the factory into the controller and access the feature simply and easily.

    
03.01.2017 / 03:52