Post e Put com Restangular para api Ruby on Rails

Asked

Viewed 131 times

1

I’m creating an app single page using Angularjs using an API ruby on Rails and the plugin restangular to effect my requests.

Problem:

The default API expects POST and PUT requests to arrive isolated in a property with the model name, e.g.:

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

Meanwhile the restangular perform these requests by passing the loose parameters, e.g.:

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 believe not in the best way, putting the object inside another with the model name as follows:

Doesn’t Work:

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

Works:

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

PUT

No PUT, the restangular perform the request 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 couldn’t get around the problem.

If anyone has a solution for PUT and a better solution for POST I thank you.

  • This seems to be a specific Restangular problem as you can see here: https://github.com/mgonto/restangular/issues/453

  • Thanks, I’ll see what I can do here.

1 answer

1


The solution is to use a customPUT. See below how I describe access to 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, can be a static value.

To facilitate access to Resource Rails I use service Restangular. See below for the configuration for 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;

This way you can inject Factory into the controller and easily access the resource.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.