RAILS link_to external site, url is attribute of user table, like: @users.website

thedeepfield picture thedeepfield · Feb 16, 2011 · Viewed 22k times · Source

I'm working on a website that allows users to create an account. One of the attributes when creating a user is a users personal website. When I try to use the users website like this:

<%= link_to @user.site, @user.url %>

The url that gets generated is: http://0.0.0.0:3000/www.userswebsite.com

I think this is because of the @user part of the link_to... but how can I get this to link to www.userwebsite.com ?

Answer

Voldy picture Voldy · Feb 16, 2011

You can prepend url with protocol if it's absent:

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

And then:

link_to @user.site, url_with_protocol(@user.url), :target => '_blank'