问题
As of Rails 5, API gem is in merged in.
Now, what does that leave us with in case I have API to call via AJAX from the webpage? I'm looking for a best practice here. Surely, I can make a route with JSON serializer myself. Then, there is a possibility to entirely separate API calls into another app.
Since API functionality is called by inheritance class ApplicationController < ActionController::API
I can't really see an option to combine the it with standard ApplicationController < ActionController
call.
Am I right? Would overloading on per-controller basis work?
回答1:
If you use the --api
mode I think that you are right - you could not combine those. And this is made by design - ActionController::API
is a subclass of ActionController::Metal
. The idea is to have ActionController::API
very skinny and lightweight. But, by enabling the api mode you create a "contract" that your application will be just an API, and that is it.
But, you could always have a both, a normal and an API controller in the same application, if you are using a normal Rails app. Then, the ActionController::API
class will be available as well, so you can have an API
namespace containing only the lightweight API
controllers, and the rest in the global namespace.
For example:
class UsersController < ApplicationController
* some code here *
end
and:
class API::V1::UsersController < ApplicationController::API
* some code here *
end
Hope that helps!
来源:https://stackoverflow.com/questions/38250405/combining-api-and-web-views-in-rails-5