Wednesday, May 29, 2013

月亮沒有來

月亮沒有來
今天月亮沒有來
沒有來到我床前的窗沿
不是有霜雪的日子
不是有低頭思鄉的情結
今天月亮沒有來
平常她都是圓圓的臉
圓圓的眼
看著我入眠
月亮沒有來
我依然合著眼
靜靜的睡在沒有月亮的夜

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