Ruby on Rails with REST API

前提是你 提交于 2019-12-22 11:28:30

问题


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.

I have a Webservice that I want to use my rails application with. 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.

However, I would have to replicate all of the logic provided by the webservice(which isn't trivial). 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
  2. Service returns 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? Or do is there a way to persist this JSON object?

回答1:


Why rails if you don't need any of its features? I'd recommend start with Sinatra, then add the libraries you need, as JSON, ActiveRecord(?) that Rails ships with.

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. How is this title related to the question? Why direct DB? You don't want to instantiate a User-object and then do a user.to_json on it?

KISS! :)




回答2:


ActiveResource handles your use case just fine 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.

class User < ActiveResource::Base
end

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


来源:https://stackoverflow.com/questions/4426467/ruby-on-rails-with-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!