在 Rails 5 中结合 API 和 Web 视图 [英] Combining API and web views in Rails 5

查看:32
本文介绍了在 Rails 5 中结合 API 和 Web 视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Rails 5 开始,API gem 已合并.

As of Rails 5, API gem is in merged in.

现在,万一我有 API 可以从网页通过 AJAX 调用,这会给我们带来什么?我在这里寻找最佳实践.当然,我可以自己使用 JSON 序列化程序创建路由.然后,有可能将 API 调用完全分离到另一个应用程序中.

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.

由于 API 功能是通过继承调用的 class ApplicationController <;ActionController::API 我真的看不到将它与标准 ApplicationController < 结合的选项.ActionController 调用.

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?

推荐答案

如果您使用 --api 模式,我认为您是对的 - 您无法将它们结合起来.这是设计使然 - ActionController::APIActionController::Metal 的子类.这个想法是让 ActionController::API 非常瘦和轻巧.但是,通过启用 api 模式,您创建了一个合同",您的应用程序将只是一个 API,仅此而已.

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.

但是,如果您使用的是普通 Rails 应用程序,则始终可以在同一应用程序中同时拥有普通控制器和 API 控制器.然后,ActionController::API 类也将可用,因此您可以拥有一个仅包含轻量级 API 控制器的 API 命名空间,并且其余在全局命名空间中.

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.

例如:

class UsersController < ApplicationController
  * some code here *
end

和:

class API::V1::UsersController < ApplicationController::API
  * some code here *
end

希望有帮助!

这篇关于在 Rails 5 中结合 API 和 Web 视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆