tdog
tdog

Reputation: 147

Rails: Having a small issue with link_to and external URLs

Pretty new to rails. I'm doing a project where a user submits a url and a title. The title is supposed to link to the url provided by the user. The url is stored as a param for link.

Here's the code from the index view:

<% @links.each do |link| %>
  <%= link_to link.title, link.url %>
  <%= link_to "comments", link %>
<% end %>

This works, for the most part.

The problem occurs if the submitted url doesn't begin with http://. As it is, it's pointing to http://localhost:3000/google.com and I get an error No route matches [GET] "/google.com"

How could I get around this? I tried changing it to:

<%= link_to link.title, "http://#{link.url}" %>

Which makes google.com work, but then http://google.com turns into http://http//google.com somehow.

I'm sure the fix will be a face palm moment!

Upvotes: 0

Views: 226

Answers (2)

MilesStanfield
MilesStanfield

Reputation: 4639

Prepend url with protocol if it's absent:

module ApplicationHelper
  def url_with_protocol(url)
    /^http/i.match(url) ? url : "http://#{url}"
  end
end

<%= link_to link.title, url_with_protocol(link.url) %>

answer derived from this SO question/answer

Upvotes: 1

Jefferson
Jefferson

Reputation: 1559

In your input field, you can do something like <input type="text" name="url" value="http://"> so that your url will always started with http://. User can also manually changed it to https if needed.

Also I may add a full_url method to the model that adds it if it's missing.

Upvotes: 1

Related Questions