Dav*_*les 3 ruby-on-rails url-routing
我有以下形式的 Rails 路线
get '/:collection/*files' => 'player#index'
Run Code Online (Sandbox Code Playgroud)
其中files旨在是以分号分隔的媒体文件列表,例如/my-collection/some-video.mp4%3Bsome-audio.mp3
这些由以下形式的控制器操作处理:
class PlayerController < ApplicationController
def index
@collection = params[:collection]
@files = params[:files].split(';')
end
end
Run Code Online (Sandbox Code Playgroud)
<audio>并使用显示每个文件的 HTML5或元素的模板进行渲染<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: []
基于这个答案,我向路线添加了正则表达式约束:
class PlayerController < ApplicationController
def index
@collection = params[:collection]
@files = params[:files].split(';')
end
end
Run Code Online (Sandbox Code Playgroud)
这解决了No Route matches 的问题,但现在多个分离的版本也会因缺少模板而失败。(无论如何,这并不理想,因为我仍然宁愿允许/文件值。但/.*/效果并没有更好。)
我尝试过format: false,有或没有constraints,但仍然缺少模板。
我还尝试了普通路径参数 ( /:collection/:files),并得到了与通配符相同的行为*files。
我怎样才能让 Rails 忽略并通过这条路线的扩展?
注意:我在 Ruby 2.5.1 上使用 Rails 6.0.0。
在这个 Rails 问题的讨论之后,神奇的公式似乎被添加defaults: {format: 'html'}到format: false:
get '/:collection/:files',
to: 'player#index',
format: false,
defaults: {format: 'html'},
constraints: {files: /.*/}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1020 次 |
| 最近记录: |