【发布时间】:2020-01-13 16:14:25
【问题描述】:
我有一个 Rails 路由的形式
get '/:collection/*files' => 'player#index'
其中files 旨在成为以分号分隔的媒体文件列表,例如/my-collection/some-video.mp4%3Bsome-audio.mp3
这些由以下形式的控制器操作处理:
class PlayerController < ApplicationController
def index
@collection = params[:collection]
@files = params[:files].split(';')
end
end
并使用为每个文件显示 HTML5 <audio> 或 <video> 元素的模板进行渲染。
只要文件没有扩展名就可以正常工作,例如
/my-collection/file1%3Bfile2.
但是,如果我添加文件扩展名,
/my-collection/foo.mp3%3Bbar.mp4,
我明白了:
没有路线匹配 [GET] "/my-collection/foo.mp3%3Bbar.mp4"
如果我尝试使用单个文件,例如/my-collection/foo.mp3,我明白了:
PlayerController#index 缺少此请求格式和变体的模板。 request.formats: ["audio/mpeg"] request.variant: []
基于this answer,我在路由中添加了一个正则表达式约束:
get '/:collection/*files' => 'player#index', constraints: {files: /[^\/]+/}
这解决了无路由匹配问题,但现在多个分离的版本也因缺少模板而失败。 (无论如何这并不理想,因为我仍然宁愿在文件值中允许/。但/.*/ 并没有更好的工作。)
我尝试了format: false,有和没有constraints,但仍然缺少模板。
我还尝试了一个普通的路径参数 (/:collection/:files),得到了与通配符 *files 相同的行为。
如何让 Rails 忽略并通过此路由的扩展?
注意:我在 Ruby 2.5.1 上使用 Rails 6.0.0。
【问题讨论】: