2

I have been pondering about developing a new application with rails (probably without models?). What I meant is; backend will be written in any other language and that will provide the RESTful APIs, which will be consumed by Rails app.

Since backend API will take care of all data CRUD actions and rails app will not have access to database directly. So there is no use of rails model in such architecture?

I can directly make curl call to APIs from controllers too, but I wish to keep my controller skinny while fat models.

Or other way, API curl calls can be made in the models and it can behave like data CRUD being done to the database in that model.

In any of above scenarios, I will not be able to get benefit of many rails features or gems (such as friendly_id) which works on active records/ORM.

I am really confused as which way I should go? And what is the best practice? What architecture you can suggest? I definitely wants to keep my backend completely decoupled and providing only RESTful apis only.

Thanks in advance.

4

1 回答 1

4

Take a look at ActiveResource.

You'll end up with models, but most will only take up one line.

Say your api service has a url like: http://api.fart.com/products.json which spits out a list of products. In your rails app that will be consuming this data, create a Product model inheriting from ActiveResource. First, set your api url for activeresource.

class ActiveResource::Base
  self.site = "http://api.fart.com"
end

Next, define a Product class.

class Product < ActiveResource::Base; end

Now, in your controllers, you can do:

Product.all

And it should hit "http://api.fart.com/products.json" and return the good stuff.

Obviously this is a quickly contrived example, but I have recently used it for a similar situation and it worked great.

///////////////

see example applications for basic concept.

///////////////

Per your questions and your pull requests on github I understand what you are trying to do now. ActiveResource does not come with a where method - however, it's find method has an options argument that supports a params hash.

Rails controller with query params

def index
  @products = Product.find :all, params: { country: "Brazil", price: 500 }
end

This will hit our Sinatra route at api.fart.com/products.json?country=Brazil&price=500

# Assume we are using ActiveRecord/DataMapper or the like
get "/products.json" do
  @products = Product.where country: params[:country], price: params[:price].to_i
  json products: @products
end
于 2012-10-24T06:34:21.717 回答