在 Rails 路由中抑制文件扩展名检测/格式映射 [英] Suppress file extension detection / format mapping in Rails route

查看:49
本文介绍了在 Rails 路由中抑制文件扩展名检测/格式映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单的 Rails 路由

I have a Rails route of the form

get '/:collection/*files' => 'player#index'

其中 files 旨在以分号分隔的媒体文件列表,例如/my-collection/some-video.mp4%3Bsome-audio.mp3

where files is intended to be a semicolon-separated list of media files, e.g. /my-collection/some-video.mp4%3Bsome-audio.mp3

这些由以下形式的控制器操作处理:

These are handled by a controller action of the form:

class PlayerController < ApplicationController
  def index
    @collection = params[:collection]
    @files = params[:files].split(';')
  end
end

并使用为每个文件显示 HTML5 元素的模板呈现.

and rendered with a template that displays an HTML5 <audio> or <video> element for each file.

只要文件没有扩展名,这就可以正常工作,例如/my-collection/file1%3Bfile2.

This works fine so long as the files have no extension, e.g. /my-collection/file1%3Bfile2.

但是,如果我添加文件扩展名,/my-collection/foo.mp3%3Bbar.mp4,我得到:

However, if I add the file extensions, /my-collection/foo.mp3%3Bbar.mp4, I get:

没有路由匹配 [GET] "/my-collection/foo.mp3%3Bbar.mp4"

如果我尝试使用单个文件,例如/my-collection/foo.mp3,我得到:

And if I try it with a single file, e.g. /my-collection/foo.mp3, I get:

PlayerController#index 缺少此请求格式和变体的模板.request.formats: ["audio/mpeg"] request.variant: []

基于这个答案,我向路由添加了正则表达式约束:

Based on this answer I added a regex constraint to the route:

  get '/:collection/*files' => 'player#index', constraints: {files: /[^\/]+/}

这解决了没有路由匹配的问题,但现在多个分离的版本也因缺少模板而失败.(无论如何这并不理想,因为我仍然希望在文件值中允许 /.但是 /.*/ 并没有更好的工作.)

This solves the No route matches problem, but now the multiple, separated version also fails with missing a template. (It's not ideal anyway, since I'd still rather allow / in file values. But /.*/ didn't work any better.)

我尝试了format: false,有和没有约束,但仍然缺少模板.

I tried format: false, with and without constraints, and still got missing a template.

我还尝试了一个普通的路径参数(/:collection/:files),并得到了与通配符 *files 相同的行为.

I also tried an ordinary path parameter (/:collection/:files), and got the same behavior as for the wildcard *files.

如何让 Rails 忽略并通过此路由的扩展?

How can I get Rails to ignore and pass through the extension for this route?

注意:我在 Ruby 2.5.1 上使用 Rails 6.0.0.

Note: I'm using Rails 6.0.0 on Ruby 2.5.1.

推荐答案

关注 这个 Rails 问题,神奇的公式似乎是将 defaults: {format: 'html'} 添加到 format: false:

Following the discussion on this Rails issue, the magic formula appears to be adding defaults: {format: 'html'} to format: false:

  get '/:collection/:files',
      to: 'player#index',
      format: false,
      defaults: {format: 'html'},
      constraints: {files: /.*/}

这篇关于在 Rails 路由中抑制文件扩展名检测/格式映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆