Ruby on Rails with REST API - ruby-on-rails

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
I have a rails app that gets on URL www.mywebservice:8080.com/users/5
Service returns JSON {name:foo,nick:bar,friend:baz}
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?

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"

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! :)

Related

Integrate new rails app with existing external MS SQL Server database

I need to create a new rails application that will use an existing external Microsoft SQL server database as its primary database. This DB is running on an external server that i'll need to connect to. Here where i work there's a separate DB Admins section so im not sure what steps i need to perform. I think the easy part is connect to the server and set the app to work with that DB. But i get confused after that.
Should i create a db dump and migration?
Should i add models to represent existing database structure?
In case i need to create new models and tables in the db...
Should i generate its models from the rails generator and run migrations on the db or contact the DB admins to create the tables, and then specify manually the models inside the app? <- this really confuses me
Thank you in advance and sorry for my english! :)
EDIT!! -> The Rails Way
I've found another great way to integrate multiple database data... You can define a model and specify in which database it's located (so db connection is never closed)... This is definitely The Rails Way and should be followed...
Here's a nice tut:
Multiple Databases in Rails
TL;DR
Define your secondary_db in database.yml
Define your model and specify its database and table name
Class ExternalDatabaseModel < ActiveRecord::Base
establish_connection(:secondary_db)
self.table_name = "the_table"
self.primary_key = 'someWeirdIDColumn'
end
Then use as any other rails model, specify relationships and more :)
Hope it helps to somebody!
I would suggest you take a look at tiny tds gem: https://github.com/rails-sqlserver/tiny_tds. It's really use to config and use... you can use it to connect on your external sql server db and make the queries you want. Don't know which type of system you're working, but if you're constantly retrieving data, making external requests may get your system slower. Depending on your application, you could consider synchronizing the data, making a local database redundant. Hope it helps you, good luck!
EDIT: about the models part: if you're going to retrieve the data from that sql server every time you need, than you don't need to store it locally. But if you're doing that redundancy, you should create the models with the attributes you'll need, than when you retrieve from the server, you save it normally, just attributing the values to your model and calling save! method.

How to access multiple data sources in a single Ruby on Rails model?

The application I'm currently working on requires me to access multiple data sources from within a single model. I want to know what's the best way to accomplish it. Can I do something like the following?
class SomeModel < ActiveRecord::Base
establish_connection :data_source1
# Get some data from data_source1 and store in a instance variable
establish_connection :data_source2
# Get some data from data_source2 and store in a instance variable
end
Appreciate for your suggestions.
This is a super bad idea as #jvillian has said. What you want here is two different models each connected to their respective data source, something ActiveRecord does allow by default.
That part can be a bit tricky but won't confuse ActiveRecord.
The big issue here is it prefers to cache the schema when it connects and persists that for the life of the process. If the databases differ in any way you'll have chaos, plus if you keep switching the connection you may completely mess up the transaction planner which has to take into account which models live in which database for rollback purposes.

Correct rails place for no-db data fetching code

I'm looking for the "rails" design pattern for code that fetches data from other websites.
I have a rails controller in my app that fetches data not from the database, but from external API's or scraped from the web.
Where's the "rails" place to put this code.
For quick implementation, I just stuck it in a model, but the model doesn't interact with the database - or support standard model functionality - so that feels wrong, but my understanding of rails and ruby isn't yet solid enough to know where it should go.
The way the code works roughly is
controller calls model.fetchData args
the model uses HTTParty or similar to make the call
processes data
passes it back to the controller
Any advice?
Broadly-speaking I think there are two possible ways to do this:
Create a plain ruby class to contain the methods for making requests to the API(s) and processing responses from it(them). You can include the HTTParty module in this class with include HTTParty. The usual place to put this code is in lib/ (make sure that wherever you put it, the path is in autoload_paths).
If you're doing anything really complex, or the API itself is complex, you might want to consider creating a separate gem to handle interaction with the API(s). The term for this type of gem is an "API wrapper" -- if you look around, you'll see there are lots of them out there for popular services (Twitter, LinkedIn, Flickr, etc.)
Notice I haven't mentioned activerecord. If you're not going to be saving anything to the DB, I don't see any need to even create any activerecord models. You can get by with just controllers and views, and then (if needed) pick and choose components from activemodel (validations, internationalization, etc.) to make your ruby API wrapper class feel more like a Rails model. For example, one thing that I've done in an app I'm working on is to apply validations to query strings before actually making requests to an external API, which is a bit like running validations on database queries before querying a DB. See this article by Yehuda Katz for more on how to make plain ruby objects feel like activerecord models.
Hope that helps. I answered another question very similar to this one just yesterday, you might want to have a look at that answer as well: Using rails to consume web services/apis

Preserve external changes in CouchDB with CouchRest Model

I'm using couchrest_model to manage some DBs in Rails. So far, it worked like a charm, but I noticed that if I PUT some data via HTTP request, CouchRest Model doesn't seem to realise that the changes are made, so it wipes off the whole record. Of course, I can see the changes in Futon, but not in Rails. When I enter the console, the previously saved instance is just not there.
Of course, I could use HTTP all the way, but I'd really like to make use of validations and other goodies that are available in ActiveRecord class.
Is there any chance that I can make these two guys work together?
P.S.
If you think/know that this approach will work with any other CouchDB Ruby/Rails gem, please, do tell! =)
I've mentioned CouchRest Model because IMO it's the most up-to-date and advanced gem out there.
I realised that this one was so damn easy, it's just that I was using the wrong tool (apart from being a proper n00b). AFAICT, it's not possible to use CouchRest Model solely to carry out persistent operations on CouchDB backend. All external calls that alter the database record(s) in certain way will somehow "remove" that record from ActiveARecord. Instead, you'd probably like to use CouchPotato, since it supports persistent operations.
I'll be glad to give checkmark if anyone comes up with vaguely better idea that this one.

Unique responses rails gem

I like to determine if a visitor has already submitted a form.
I was thinking of doing a couple of things:
cookie
ipaddress
requiring login (much less desirable since the signup barrier might dissuade visitors)
Is there a ROR gem for this? If so please post a link.
Thanks
How are you intending on saving the data?
If you're planning on putting this into a model, great. Then you can create some form of unique value (I'd probably base it on an MD5 of IP address and user agent), store that in a field, and require it to be unique for each submission.
There probably is a gem for this, but it's pretty simple anyway.
If you're not putting it into a model, I think we need more details of what your intentions are.
This sounds like a great opportunity to use HTML5's local storage engine.
You can store up to ~5MB and it's persistent.
YUI has a good wrapper for it.
http://developer.yahoo.com/yui/storage/

Resources