2014-07-11 73 views
1

我正在構建一個使用RABL的rails應用程序,該應用程序在Active Admin控制的數據上生成一個API。這是一個非常簡單的API,我沒有太多數據,但是我對Angular.js和客戶端應用程序更新。使用rabl,我在2個對象上創建一個API。這是我的代碼到目前爲止;如何使用Angular.js來使用Rails RABL API?

project.rb

class Project < ActiveRecord::Base 

    has_attached_file :image, :styles => { :small => "100x100", :medium => "200x200", :large => "300x300" }, 
       :url => "/system/members/:id/:style/:basename.:extension", 
       :path => ":rails_root/public/system/members/:id/:style/:basename.:extension" 
    validates_attachment :image, content_type: { content_type:  ["image/jpg", "image/jpeg", "image/png"] } 

end 

projects_controller.rb

class ProjectsController < ApplicationController 

def index 
    @projects = Project.all 

    respond_to do |format| 
     format.json { render } 
    end 
end 

視圖/項目/ index.html.rabl

collection @projects 
attributes :id, :title, :short_description, :long_description, :client, :image 

member.rb

class Member < ActiveRecord::Base 

    has_one :image 

    has_attached_file :image, :styles => { :small => "100x100", :medium => "200x200", :large => "300x300" }, 
       :url => "/system/members/:id/:style/:basename.:extension", 
       :path => ":rails_root/public/system/members/:id/:style/:basename.:extension" 
    validates_attachment :image, content_type: { content_type:  ["image/jpg", "image/jpeg", "image/png"] } 

end 

members_controller.rb

class MembersController < ApplicationController 

    def index 
     @members = Member.all 

     respond_to do |format| 
      format.json { render } 
     end 
    end 

    end 

視圖/構件/ index.html.rabl

collection @members 
attributes :id, :name, :title, :bio, :facebook, :twitter, :instagram, :linkedin, :dribbble, :image 

角度;

應用程序/資產/ Java腳本/ app.js

var app = angular.module("onyx", ["ngResource"]); 

app.factory("Member", [ //member for the member object 
    "$resource", function($resource) { 
    return $resource("/member/:name", { //trying to just start by getting the name 
     name: "@name" 
    }, { 
     update: { 
     method: "GET" 
     } 
    }); 
    } 
]); 

更新: 由於this夢幻般的教程中,我得到了一切工作。

回答

0

因爲我已經用角和Rails做了幾個應用程序很好的解釋。一旦你創建你的應用程序,就可以爲你的所有數據生成一個API。一旦你做了Angular照顧其餘的。在我看來,使用寶石並不是最好的,您可以通過使用CDN角度來使用rails資產管道來獲得您的優勢。

我發現學習如何讓軌道和角度發揮好起來,是這兩個教程最好的資源:

  1. http://coderberry.me/blog/2013/04/22/angularjs-on-rails-4-part-1/(2份)
  2. http://angular-rails.com(完整的應用程序演練+部署和TDD)
3

您可以使用restmod,一個很棒的ORM for angular。

「Restmod創建的對象可以在Angular中使用,與您的RESTful API進行交互。」

首先你需要安裝它。在github這很好解釋。

然後,您可以定義一個模型。例如:

module.factory('Project', function($restmod) { 
    return $restmod.model('/projects'); 
}); 

然後,你可以注入你的控制器/服務/等項目模型,並用它作爲以下

$scope.projects = Project.$search(); 

在你的看法,你可以做這樣的事情:

<pre>{{projects | json }}</pre> 

查看結果。

隨着restmod您可以:

  • 創建模型和關係
  • 執行CRUD操作
  • 搜索和過濾器集合
  • 您的模型創建自定義的方法,混入和掛鉤。

所有它在github pagedocumentation page

+0

我更喜歡Restangular的樂趣:https://github.com/mgonto/restangular –