1

Currently when a user in my app creates a new job post they enter a URL that links to their job page on their website. I then want to use this to link out to their site.

It is stored in my DB asjob.job_url and I have defined an object @link in my controller to find the job and relevant URL.

I currently have the following code to loop through all jobs and provide links:

 <section id="job-wrapper">
   <% @jobs.each do |job| %>
    <%= link_to @link.job_url do %>
       <%= job.title %>
       <%= job.location %>
       <%= job.job_type %>
       <%= job.salary %>
       <%= job.company %>
   <% end %>
  <% end %>
 </section>

The issue I am having is that without the URL containing http:// rails assumes that the link is internal and so produces a link like localhost:3000/www.google.com.

Is there a way for me to ensure Rails only ever recognises the link as external in the instance? Alternatively could someone explain how I can add http:// to all links on creation unless the user has already stated it?

Thanks in advance for your help!

Tom Pinchen
  • 2,467
  • 7
  • 33
  • 53
  • 1
    http://stackoverflow.com/questions/5012188/rails-link-to-external-site-url-is-attribute-of-user-table-like-users-websit – Mike Campbell Aug 02 '12 at 14:44
  • check http://stackoverflow.com/questions/5012188/rails-link-to-external-site-url-is-attribute-of-user-table-like-users-websit – rails_id Aug 02 '12 at 14:45
  • To ensure that your user prefixes all url with `http://`, I suggest you write a custom validator. These links will help: 1) [http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-validators ] and 2) [http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url] – Gooner Aug 02 '12 at 14:55

1 Answers1

2

Thanks for all your help!

I managed to solve this by creating a new helper called URLhelper

This contained:

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

I then just used the following link_to

 <%= link_to url_with_protocol(@link.job_url), :target => '_blank' do %>

Thanks

Tom Pinchen
  • 2,467
  • 7
  • 33
  • 53