LoginSignup
46

More than 5 years have passed since last update.

Railsのルーティングとフォーマット

Last updated at Posted at 2012-04-12

APIのルーティングでサブドメインをapiにする制約をつけてみました。

routes.rb
constrains subdomain: 'api' do
  resources :users
end

これで、api.domain.com/users/1とかで取得できるのですが、そのままだとhtmlが返ってきちゃいます。
もちろんapi.domain.com/users/1.jsonとかすればいいんですが、オープンなAPIにするならフォーマット指定しなきゃhtmlが返ってきてしまうAPIというのも罠臭いなーと。

constrainsはformatの制約も課せるので、

routes.rb
constrains subdomain: 'api', format: :json do
  resources :users
end

とすれば、api.domain.com/users/1.htmlのルーティングにヒットしなくなります。
あとはApplicationControllerに

application_controller.rb
  before_filter :set_api_format

private
  def set_api_format
    if request.subdomain == 'api' and request.format == :html
      request.format = :json
    end
  end

とすれば、api.domain.com/users/1.htmlはルーティングにヒットされなくなり、
api.domain.com/users/1api.domain.com/users/1.jsonとして処理されます。

jsonだけでなくxmlもサポートしたいのならば、constrainsのformatにxmlを増やして、各アクションで対応するだけです。
jsonだけなら基本的にアクションは書き換え無しで動きます。

また、サブドメインがapiでないURLで.jsonがヒットするのはややこしいので、
一般のルーティングをconstrains format: :htmlの中に置けばOKです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46