Thursday, May 2, 2013

Rails , Angular and REST resource example.

I work on an rails application and trying to use angular with REST API.
Here I document what I do to make it work:
1. In layout view's head.

  <%= csrf_meta_tag %>
2. In javascript using ng-app module to update httpProvider add csrf token in the header.
var vmShowApp = angular.module('vmShowApp', ['ngResource']);
  vmShowApp.config([
    "$httpProvider", function($httpProvider) {
      $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
    }
  ]);
3.In html page to do the update , it will call update function using ng-click.
<a class="action" href="" ng-click="update('<%= Vm::STATUS[:VM_STATUS_AVAIL] %>')"><%= Vm::STATUS[:VM_STATUS_AVAIL] %></a>
4. In javascript it define update function, looks like angular will create vm object inside this put request, so I add the status inside this vm object.
$scope.update = function(status){
      $scope.vm['status'] = status;
      var vm = Vm.get({id:<%= @vm[:id] %>});
      vm.vm = {}
      vm.vm.status = status;
      vm.$update({id:<%= @vm[:id] %>});
      }; 

5. In config/route.rb define the REST rerouces.
namespace :api do
    namespace :v1 do
      resources  :vms
    end
  end

6.In app/controllers/api/v1/vms_controller.rb define the update function
def update
 respond_with Vm.update(params[:id],params[:vm])
end

No comments: