我试图让Angular JS和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
答案 0 :(得分:1)
更新您的route.rb
以默认呈现JSON而不是HTML
resources :entities, defaults: {format: :json}