我有一个 Rails 3.1 应用程序,我想为其创建一个 API。我希望我的网址看起来像:
www.example.com/controller/action // Normal Web requests
api.example.com/controller/action.json // API requests
第一个用于正常请求,另一个显然用于我的 API 内容。我希望这两个都映射到同一个 Controller / Action 。
如何设置我的应用程序,使其在 www 上时仅响应 HTML,而在 api 子域上时仅响应 json、xml 等?
最佳答案
最简单的方法 (imo) 是使用 Rails 3 路由约束。在 config/routes.rb 中,使用:
constraints :subdomain => 'www', :format => :html do
# Routing for normal web requests
match 'mycontroller/:action' => 'mycontroller#index'
# ...
end
constraints :subdomain => 'api', :format => :json do
# Routing for API requests
match 'mycontroller/:action.:format' => 'mycontroller#index'
# ...
end
您可能还想查看 respond_with (以及类级别的 respond_to),这使得编写响应多种格式的 Controller 比使用传统的 respond_to 更容易。
关于ruby-on-rails - Rails 3.1 API 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8143487/