简体   繁体   English

带有REST API的Ruby on Rails

[英]Ruby on Rails with REST API

I am new to the Ruby on Rails thing, and while I like the organization and standards provided, I am a little confused on how to make rails work for me in this specific case. 我是Ruby on Rails的新手,虽然我喜欢所提供的组织和标准,但是在如何使Rails在这种特定情况下对我有用的过程上,我有些困惑。

I have a Webservice that I want to use my rails application with. 我有一个要与Rails应用程序一起使用的Web服务。 Making a direct connection to the database would be nice and provide me instantly with the models I need to make my Rails application work. 直接连接到数据库会很好,并且可以立即为我提供使Rails应用程序正常工作所需的模型。

However, I would have to replicate all of the logic provided by the webservice(which isn't trivial). 但是,我将必须复制webservice提供的所有逻辑(这并非不重要)。 If I didn't make a direct connection to the database, how would I persist the models(such as a user model). 如果我没有直接连接到数据库,我将如何持久化模型(例如用户模型)。

Would I have to make a separate database that mimics the server's DB but never actually interacts with it directly? 我是否必须创建一个单独的数据库来模拟服务器的数据库,但实际上从未直接与其交互?

Thanks in advance -- let me know if you need clarification. 预先感谢-如果需要澄清,请告诉我。

EDIT: Example 编辑:示例

  1. I have a rails app that gets on URL www.mywebservice:8080.com/users/5 我有一个URL上的Rails应用程序www.mywebservice:8080.com/users/5
  2. Service returns JSON {name:foo,nick:bar,friend:baz} 服务返回JSON {name:foo,nick:bar,friend:baz}
  3. At this point how do I tell rails to make a User object out of what it just got and then store it in the database? 在这一点上,我如何告诉Rails从刚得到的对象中创建一个User对象,然后将其存储在数据库中? Or do is there a way to persist this JSON object? 还是有办法持久化此JSON对象?

ActiveResource handles your use case just fine http://api.rubyonrails.org/classes/ActiveResource/Base.html ActiveResource可以很好地处理您的用例http://api.rubyonrails.org/classes/ActiveResource/Base.html

What it does is reflect on the json returned by the service and fake out the object to make it look like it's a real object. 它所做的是反映在服务返回的json上,并伪造对象以使其看起来像是真实对象。

class User < ActiveResource::Base
end

user = User.find(1) 
puts user.name  
# "scott"

Why rails if you don't need any of its features? 如果您不需要它的任何功能,为什么要使用Rails? I'd recommend start with Sinatra , then add the libraries you need, as JSON, ActiveRecord(?) that Rails ships with. 我建议从Sinatra开始,然后添加所需的库,作为Rails附带的JSON,ActiveRecord(?)。

You may connect to any database you want and you don't have to use ActiveRecord, however, it's hard to understand what you're really asking. 您可以连接到所需的任何数据库,而不必使用ActiveRecord,但是,很难理解您的真正要求。 How is this title related to the question? 这个标题与问题有什么关系? Why direct DB? 为什么要直接DB? You don't want to instantiate a User-object and then do a user.to_json on it? 您不想实例化用户对象,然后在其上执行user.to_json吗?

KISS! 吻! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM