2017-03-07 38 views
0

我正在学习如何使用RoR编写一个restful API并且有一个与它相关的问题。所以,我会解释我与代码一起做了什么。带栏杆的Restful api

这是我的控制器看起来像:

class EmployeesController < ApplicationController 
    require 'rest_client' 

    def index 
    uri   = "localhost:3000/employees" 
    rest_resource = RestClient::Resource.new(uri) 
    users   = rest_resource.get # will get back you all the detail in json format, but it will we wraped as string, so we will parse it in the next step. 
    @users = JSON.parse(users, :symbolize_names => true) # convert the return data into array 
    @users.each do |u| 
     logger.info(u.id) 
    end 
    # return based on the format type 
    respond_to do |format| 
     format.json {render json: @users} 
     format.xml {render xml: @users} 
     format.html 
    end 
    end 

在我的Gemfile,我已经包含了其他的客户端也是如此。

gem 'rest-client' 

我的路线是: 根的员工#指数“ 资源, '雇员'

希望一切都很好至今。

现在,当我送:

- >卷曲请求 'http://localhost:3000/employees',它卡住。

- >在'http://localhost:3000/'获取请求(通过在浏览器中输入),它也陷在这里。

我失踪的是什么?

+0

'/ employess'命中EmployeesController#索引吗? – Santhosh

+0

@Santhosh,是的,它击中了那个。 –

+0

是不是一个无限循环? – Santhosh

回答

1

您不需要RestClient,因为您正在此处编写服务器,而不是客户端。浏览器充当客户端。删除对本地主机的调用,因为它正在创建一个循环。

的URL,这应该已经在你的routes.rb设置,也许使用:假设这是一个典型的应用

resources :users 

,展会功能应该从数据库中使用ActiveRecord阅读。

class EmployeesController < ApplicationController 
    def index 
    @users = User.all 
    respond_to do |format| 
     format.json {render json: @users} 
     format.xml {render xml: @users} 
     format.html 
    end 
    end 
end 
+0

我正在尝试'卷曲'以及我想我会需要一个休息客户端。合理? –

+0

@mahemoff,我不明白。为什么我要将'用户'声明为资源? –

+0

如果您试图制作从数据库读取用户的标准服务,则无需卷曲。服务器从数据库获取数据,而不是其他服务。然后,您可以通过将浏览器指向http:// localhost:3000 – mahemoff

0

你有一些其他的应用程序在localhost:3000上运行吗?因为如果没有,那么你的服务器一次又一次地调用自己,造成一个循环。

如果你确实有一些其他应用程序,它从数据库中提取用户,那么确保它运行在其他一些端口上,而不是你的rails应用程序。

如果你只有1个应用程序,那么你不需要休息客户端。

0

你实际上可以做到这一点,没有任何额外的宝石。您只需根据要公开给API用户的声明来声明路由,并相应地返回类型(xml,json,...)。