ruby-on-rails 将多条路径导入同一个操作?

guykilcj  于 7个月前  发布在  Ruby
关注(0)|答案(2)|浏览(46)

我提交了我的网站Map到谷歌作为example.com/sitemap其中example.com是我的域看着我的服务器访问日志请求进入sitemap.txt和sitemap.xml我可以只添加路由sitemap.txt和sitemap.xml为3个路由到同一个控制器动作?我想到了“重定向”,但我不认为它适用
当我已经向/sitemap发送请求时,我应该如何处理对sitemap.xml和sitemap.txt的请求

3pmvbmvn

3pmvbmvn1#

你不需要做任何事情,Rails会自动处理扩展。
假设你有一条这样的路线:

# Both of these options generate the same routes
get :sitemap, to: 'sitemaps#show'
resource :sitemap, only: :show

字符串
如果运行rails routes -c sitemap,可以看到它与模式/sitemap(.:format)匹配。

Prefix Verb URI Pattern        Controller#Action
sitemap GET  /sitemap(.:format) sitemaps#show


要响应各种格式,您可以为每种格式创建视图,如果您正在做的非常简单,则使用implicit rendering

class SitemapsController < ApplicationController
  # GET /sitemaps.txt
  # GET /sitemaps.xml
  def show
    # this is optional but it can be good to enumerate which formats 
    # you should actually accept
    respond_to :txt, :xml
  end
end


这将呈现app/views/sitemaps/show.#{format}.html.erb
或者你可以使用MimeResponds来显式地处理每种类型:

class SitemapsController < ApplicationController
  # GET /sitemaps.txt
  # GET /sitemaps.xml
  def show
    respond_to do |format|
      format.txt { ... }
      format.xml { ... }
    end
  end
end


例如,如果你生成的XML没有视图,这是个好主意,或者你甚至可以通过省略块来混合。

olmpazwi

olmpazwi2#

是的,你肯定可以轻松地路由到同一个动作,文件后缀(.xml,.txt,.html等)被定义为路由文件中的参数。例如,你可以这样定义一个路由:

# config/routes.rb
get 'sitemap(.:format)', to 'sitemap.index'

字符串
在您的SitemapController中,index方法将接收一个params散列,其中包括:format键,值为'xml','txt','html'。这是否满足您的需求?

相关问题