我試圖讓Angular JS和Ruby on Rails在示例應用程序中共享一些數據進行通信。Ruby on Rails中的響應方法
我生成的資源稱爲Entries
,並取得該控制器:
class EntriesController < ApplicationController
respond_to :json
def index
respond_with Entry.all
end
def show
respond_with Entry.find(params[:id])
end
def create
respond_with Entry.create(params[:entry])
end
def update
respond_with Entry.update(params[:id], params[:entry])
end
def destroy
respond_with Entry.destroy(params[:id])
end
end
這產生在JSON與Entries
數據的響應。我種了Entries
數據庫:
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Entry.create!(name: "name1")
Entry.create!(name: "name2")
Entry.create!(name: "name3")
Entry.create!(name: "name4")
Entry.create!(name: "name5")
Entry.create!(name: "name6")
Entry.create!(name: "name7")
我創建了一些條目。我需要讓Angular收到它們。這是我的js文件:
var rafflerApp = angular.module('rafflerApp', ["ngResource"]);
rafflerApp.controller('RaffleCtrl', function ($scope, $resource) {
//entries list
Entry = $resource("/entries/:id", {id: "@id"}, {update: {method: "PUT"}})
$scope.entries = Entry.query();
//add a name to the list
$scope.addEntry = function(entry){
entry = Entry.save($scope.newEntry);
$scope.entries.push(entry);
$scope.newEntry = {}
}
//draw a winner
$scope.selectWinner = function(draw){
pool = [];
angular.forEach($scope.entries, function(entry){
if (!entry.winner){
pool.push(entry)
}
});
if (pool.length > 0){
entry = pool[Math.floor(Math.random()*pool.length)]
entry.winner = true
entry.$update(entry)
$scope.lastWinner = entry
}
}
});
如果我嘗試應用程序,我沒有收到任何js錯誤,但列表爲空。如果我嘗試導航到/entries/(casual :id)
,我收到此錯誤:
ActionController::UnknownFormat in EntriesController#index
,它突出了這部分代碼:
def index
respond_with Entry.all
end
爲什麼我收到這個錯誤?我如何讓Ruby on Rails與Angular JS交流數據?我也將我的路線文件:
Rails.application.routes.draw do
resources :entries
root to: "raffle#index"
end
你嘗試訪問本地主機:從瀏覽器3000/entries.json? –
顯示你的'config/routes.rb'文件 –
@SahilGrover是的,我試圖導航到我的瀏覽器,它的工作 – giovaZ