如何根据域名更改视图格式

jjm*_*res 1 rest ruby-on-rails

我想知道是否有任何方法可以更改基于域名相同rails应用程序的视图格式.

例如 :

  • www.domain.com => respond_to format.html
  • api.domain.com => respond_to format.xml或format.json

感谢你的帮助

Sim*_*tti 5

是的,在控制器中使用before_filter并response.format根据值设置request.host.

class Controller < ActionController::Base

  before_filter :adapt_response_format

  protected

    def adapt_response_format
      response.format = case request.host
        when "xml.foo.com" then :xml
        else                    :html
    end

end
Run Code Online (Sandbox Code Playgroud)