0

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!

tdog
  • 147
  • 2
  • 10

2 Answers2

1

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.

Jefferson
  • 1,559
  • 1
  • 18
  • 24
  • Thanks, this works, but what if the user is annoying and deletes the `http://` from the field before submitting, then get that error? – tdog Feb 05 '16 at 02:02
  • @tdog Then I would do the same thing as the answer below showed. To prepend the url if it's absent. I would say it's better to have `http://` included in frontend, and backend to be a safe check to see if i need to prepend the url or not. – Jefferson Feb 05 '16 at 02:06
  • Thanks, got it working smoothly now :) Learning something every day! – tdog Feb 05 '16 at 02:51
1

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

Community
  • 1
  • 1
MilesStanfield
  • 4,571
  • 1
  • 21
  • 32