在 Ruby on Rails 路由中将 url 作为参数传递

Bai*_*ith 4 url routes ruby-on-rails

我试图在 Ruby on Rails 中将音频 URL 作为参数传递,并且谷歌搜索“如何在 url 中传递 url”已被证明是有问题的。问题是我只能得到要返回的 url 减去一个关键的正斜杠。

我的路线看起来像:

get 'my_page/:title/*url', to: 'my_page', action: 'show'
Run Code Online (Sandbox Code Playgroud)

该变量在控制器中定义如下:

@url=params[:url]
Run Code Online (Sandbox Code Playgroud)

所以请求看起来像:

www.my_app.com/my_page/im_a_title/http://im_a_url.mp3
Run Code Online (Sandbox Code Playgroud)

然而, url 变量最终导致前缀后缺少斜线:

http:/im_a_url.mp3 <--notice the missing forward slash
Run Code Online (Sandbox Code Playgroud)

值得注意的是,url 的构造变化很大,构造它们会很麻烦。(例如,有些以 http 开头,有些以 https 开头。)如何保留 url 的语法?或者有没有更好的方法来一起传递这个参数?

AJc*_*dez 6

为什么不将 url 作为必需参数传递。这样你就可以使用内置的to_query.

get 'files/:title' => 'files#show'
Run Code Online (Sandbox Code Playgroud)

并在文件控制器中

class FilesController < ApplicationController

  def show
    url = params.fetch(:url) # throws error if no url
  end

end
Run Code Online (Sandbox Code Playgroud)

您可以像这样对 url 进行编码和取消编码:

{ url: 'http://im_a_url.mp3' }.to_query
# => "url=http%3A%2F%2Fim_a_url.mp3"
Rack::Utils.parse_query "url=http%3A%2F%2Fim_a_url.mp3"
# => {"url"=>"http://im_a_url.mp3"}
Run Code Online (Sandbox Code Playgroud)