user3618353
user3618353

Reputation: 91

Safe way to load url stored in database?

What is the safest way to load a url saved in database?

window.open("<%=raw @post.url%>");

Doesn't seem to be a good idea.

Upvotes: 2

Views: 180

Answers (3)

cyonder
cyonder

Reputation: 872

<% unless @post.url.blank? %>
  <%= link_to @post.url, 'http://' + @post.url, :target => '_blank' %>
<% end %>

You may want to use this. Unless checks if URL in database is empty or not. If URL is mandatory in database, you may want to remove that part.

Extra, if you need validation for url, you may want to use a validation something like this:

  URL = /\A(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?\z/
  validates :url,
            format: {with: URL, message: 'Invalid url format. Make sure you don\'t have http:// in your link'},
            allow_blank: true

So, user will input url without http://, and you will add that http:// in html, as I showed above.

Upvotes: 0

Minato
Minato

Reputation: 4533

Since window.open opens a link in new tab there is no direct way to instruct the browser form server side to open a link in a new tab.

But you can apply a little JS hack. In your erb file do it like.

<%= link_to "Post", @post.url, {:target => '_blank', :id => "linktoclick"} %>
<script>
   document.ready = function(){
     document.getElementById("linktoclick").click();
   }
</script>

Upvotes: 1

Nathock
Nathock

Reputation: 1

How are you storing the URL in your database/where are you going to use it?

Assuming @post.url will return the url you want, then something as simple as:

<a href="<%= @post.url %>">[awesome link name]</a>

html output would be:

<a href="http://your-stored-url.com">[awesome link name]</a>

Could you provide more information on where/how the url needs to be used?

Upvotes: 0

Related Questions