14

I'm refactoring a rails app that currently uses a database and ActiveRecord so that instead of of the database, it uses a JSON API (Sinatra).

What would be the best way to refactor the models? The API will return all the same information as the database used to. Infact it IS the same database, but for scalability and multiple apps requiring access to the data, we needed to turn it into an API. Ideally only the Models will need to change and ideally I can keep some validation in the rails app.

How can I change the models so they retrieve and save their instances via API calls rather than ActiveRecord database calls?

Greg Olsen
  • 912
  • 1
  • 9
  • 14
  • if its the same database why cant your app and the api server connect to it at same time? may be same transaction thing can save you – Pritesh Jain Aug 24 '12 at 17:44
  • They technically could, but it would be bad practice to have two applications affect the same database, especially when either could have migrations that would affect the other. – Greg Olsen Aug 24 '12 at 17:54
  • yeah that will surely be an issue but i do nit think it will be a smooth sail even if you try and override the basic active record functionality. may be it may also consume equivalant time to migrate the app to api. just a loose prediction. – Pritesh Jain Aug 24 '12 at 17:59
  • Looks like the correct link now is https://solnic.codes/2011/08/01/making-activerecord-models-thin/ – rahulmishra Jun 18 '20 at 19:03

2 Answers2

15

I think you are looking for something like ActiveResource

Dom Barker
  • 1,889
  • 1
  • 16
  • 29
7

For Rails 4 checkout this:

https://github.com/whichdigital/active-rest-client

This gem is for accessing REST services in an ActiveRecord style. ActiveResource already exists for this, but it doesn't work where the resource naming doesn't follow Rails conventions, it doesn't have in-built caching and it's not as flexible in general.

0bserver07
  • 3,390
  • 1
  • 28
  • 56