【发布时间】:2013-12-04 09:48:50
【问题描述】:
尝试通过名为“api”的 API 子域在 Rails 中实现 Web 服务。
在我的hosts 文件中,我添加了一行:127.0.0.1 api.localhost
在我的routes.rb 中,我设置了子域,我只需要索引操作和少量手动添加的静态路由,通过以下方式:
namespace :api, path: '', :constraints => {:subdomain => "api"} do
resources :posts, only: :index do
collection do
get 'popular_by_day'
get 'popular_by_week'
end
end
end
还生成了对应的控制器:rails g controller api/posts
测试示例:
class Api::PostsController < ApplicationController
def index
@posts = 1
respond_to do |format|
format.json { render :json => @posts }
end
end
def popular_by_day
end
def popular_by_week
end
end
rake routes 之后我有以下内容:
popular_by_day_api_posts GET /posts/popular_by_day(.:format) api/posts#popular_by_day {:subdomain=>"api"}
popular_by_week_api_posts GET /posts/popular_by_week(.:format) api/posts#popular_by_week {:subdomain=>"api"}
api_posts GET /posts(.:format) api/posts#index {:subdomain=>"api"}
据我所知,http://api.localhost:3000/posts 的链接应该可以工作,但我收到路由错误:
没有路由匹配 [GET] "/posts"(与 /posts.json 相同)
【问题讨论】:
-
你可以尝试将 127.0.0.1 api.localhost 行更改为 127.0.0.1 api.localhost.local 吗?
标签: ruby-on-rails web-services api subdomain