[英]How to best share routes between Rails app and Rails API
I am writing my first "real" Rails app after making a few successful learning projects and I'm still a little bit iffy on best practises for App vs API routes. 在完成一些成功的学习项目之后,我正在编写我的第一个“真实” Rails应用程序,但我仍然对应用程序与API路由的最佳做法有些怀疑。 Ideally, API routes will be RESTful, mainly revolving around using resources :articles
or whatever, but I'm wondering which of the the following two scenarios is best 理想情况下,API路由将是RESTful的,主要围绕使用resources :articles
或其他任何东西,但是我想知道以下两种情况中的哪一种是最佳的
I appreciate any feedback that anyone has. 我感谢任何人的任何反馈。
The default "Rails way" is to make your models available to different clients through a single set of URIs, handled by a single set of controllers — /articles for browsers, /articles.json or /articles.xml for programmatic access. 默认的“ Rails方式”是通过一组URI(由一组控制器处理)为不同的客户端提供模型,这些URI由一组控制器处理-用于浏览器的/ articles,用于编程访问的/articles.json或/articles.xml。 You can see that in Rails' emphasis on "resources", the respond_to
mechanism in your controllers and so on. 您可以在Rails强调“资源”,控制器中的respond_to
机制等中看到这一点。
This often works very well for simpler APIs that match the CRUD semantics closely. 对于与CRUD语义紧密匹配的简单API而言,这通常效果很好。 If yours for whatever reason does not, you might be better off with separating it out. 如果由于某种原因而没有,那么最好将其分离出来。
Try starting out the simple way by sticking to this 'one controller for both' approach. 尝试通过坚持这种“一个控制器兼备”的方法来开始简单的方法。 If you like, you could use 如果您愿意,可以使用
scope '(api)' do
resources :articles
resources :authors
resources :comments
# ...
end
to add an optional '/api/' path segment to your URLs - in this case, giving you both /api/articles
and /articles
, routed to the same controller. 在您的网址中添加可选的“ / api /”路径段-在这种情况下,将/api/articles
和/articles
都路由到同一控制器。 This gives you an easy way out, should you later decide to switch to separate controllers for HTML and API access. 如果您以后决定切换到用于HTML和API访问的单独控制器,则这为您提供了简便的出路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.