3

I have a string in which users input a URL, which is later displayed in index.html. How can I turn that into a working external link? Right now, the link displays as should (e.g. www.facebook.com/tester), but when I click on the link I get a no route matches "/www.facebook.com/tester" routing error. I tried user.facebook.link but that didn't work.

I tried adding href=" " also but with no luck.

<%= link_to nil, user.facebook %>
Promise Preston
  • 24,334
  • 12
  • 145
  • 143
Tony
  • 981
  • 5
  • 16
  • 30
  • the error message said no route matches what? – Andy Oct 20 '11 at 01:02
  • @Andy no route matches "/www.facebook.com/tester". I assuming Rails thinks that the link belongs to an internal route. However, that's not what I am looking for. The link should go to another site, in this case Facebook. – Tony Oct 20 '11 at 01:03
  • 4
    If it doesn't include the "http://" part it'll think it's a relative link. Why not just use a normal `` tag or a helper that wraps one up? – Dave Newton Oct 20 '11 at 01:10
  • @DaveNewton Don't I need the <% %> for embedded ruby to displayed the string that they inputted? – Tony Oct 20 '11 at 01:16
  • Sure, but that doesn't mean you need to use a link helper (though you probably can). I keep them separate to avoid cognitive overhead (in general). `Go to facebook` – Dave Newton Oct 20 '11 at 01:27
  • Or add the `http://` part in the `link_to` helper: `<%= link_to nil, "http://#{user.facebook}" %>`. – Mischa Oct 20 '11 at 02:12
  • @DaveNewton Thanks for all the help! Last thing, what if the inputs are EITHER http:// links (e.g. http:// www.facebook...) or just the domain without the http:// (e.g. www.facebook...) in front? Only one type of the links will work. Is there a way around it which allows both types? I know this may be asking a lot, but it's okay if you don't know it or don't have time to reply. – Tony Oct 20 '11 at 07:37
  • You should be scrubbing/normalizing earlier in the process. Since you're not, we're back to a helper our method that wraps the url variable to normalize it, or a helper that wraps link_to. – Dave Newton Oct 20 '11 at 11:58

1 Answers1

6

As mentioned by @Mischa, you can add:

<%=link_to nil, "http://#{user.facebook}"%>

to have the protocol added to link.

If you need to give the link a label, say, Facebook, you can use it:

<%=link_to 'Facebook', "http://#{user.facebook}"%>`

That's all.

I hope this helps

Promise Preston
  • 24,334
  • 12
  • 145
  • 143
leenasn
  • 1,466
  • 10
  • 16
  • What if the the input varied from domains with "http:" and ones that began with "www"? The "http:" would add another "http:" to some domains and not work. Is there a way around this? – Tony Oct 20 '11 at 07:56
  • You can use scan method to check whether "http" is contained or not. For eg: `user.facebook.scan(\^http\)` should return an empty array if the string does not start with http. – leenasn Oct 20 '11 at 14:11