Bailey Smith
Bailey Smith

Reputation: 2923

Pass a url as a parameter in Ruby on Rails route

I'm trying to pass an audio URL as a parameter in Ruby on Rails, and googling "how to pass a url in a url" has proved to be problematic. The problem is that I can only get the url to return minus a crucial forward slash.

My route looks like:

get 'my_page/:title/*url', to: 'my_page', action: 'show'

The variable is defined in the controller like so:

@url=params[:url]

So the request would look like:

www.my_app.com/my_page/im_a_title/http://im_a_url.mp3

The url variable, however, ultimately results missing a slash after the prefix:

http:/im_a_url.mp3 <--notice the missing forward slash

Of note, the construction of the urls varies enough that it would be cumbersome to construct them. (Some begin with http and some https, for instance.) How do I preserve the syntax of my url? Or is there a better way to pass this parameter all together?

Upvotes: 4

Views: 3652

Answers (3)

Maged Makled
Maged Makled

Reputation: 1986

Rails 4

match 'my_page/:title/:url', to: 'my_page#show' , constraints: { url: /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}/}, via: :get, :format => false
  1. constraints will match only a regex for a url.
  2. format => false will ignore the dot part of the url

Upvotes: 1

AJcodez
AJcodez

Reputation: 34156

Why don't you pass the url as a required parameter. That way you can use the built-in to_query.

get 'files/:title' => 'files#show'

and in files controller

class FilesController < ApplicationController

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

end

You can encode the url and unencode like so:

{ 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"}

Upvotes: 6

Yuriy Goldshtrakh
Yuriy Goldshtrakh

Reputation: 2014

You should url encode the parameters before passing them in

Upvotes: 2

Related Questions