2015-07-20 58 views
0

我试图让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 
+0

你尝试访问本地主机:从浏览器3000/entries.json? –

+1

显示你的'config/routes.rb'文件 –

+0

@SahilGrover是的,我试图导航到我的浏览器,它的工作 – giovaZ

回答

1

更新您的route.rb渲染默认而不是HTML JSON

resources :entities, defaults: {format: :json} 
+0

它仍然无法正常工作。做了一些测试,我已经检查过,当我尝试从http:// localhost:3000/entries重新获取数据时,控制台日志显示此信息正在进行页面刷新[HTTP/1.1 406 Not Acceptable]。 – giovaZ

+0

什么是通过请求传递的头文件? – RAJ