Search code examples
ruby-on-railspostgresqlerblink-to

How to link_to from the content of the database in a html.erb page


I'm writing a blog post on a postgres db using ruby on rails. The content of the post in the table has some external links. I've been using the link_to method, but so far this has just printed the exact code in the browser from the html.erb file. So far I have tried:

<%= link_to 'London Coffee Festival', http://www.londoncoffestival.com %>

<% link_to 'London Coffee Festival', http://www.londoncoffestival.com %>

<%= link_to 'http://www.londoncoffestival.com'do %>London Coffee Festival<% end %>

But no of these variations seem to work...

my html.erb page:

<%= render "partials/mainnav" %>
<div class="ui fluid image"><%= image_tag "header_img_thin.jpg" %>
</div>
<div class="ui grid container"><!--Main page container-->
  <div class="row">
    <div class="twelve wide column"><!--left Column-->
      <h1><%= @article.title %></h1>
<p><%= @article.text %></p>

<h2>Comments</h2>
<% @article.comments.each do |comment| %>
<p><strong>Name</strong>
<%= comment.commenter %>
</p>

<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<% end %>

<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |f| %>
  <p>
<%= f.label :Name %><br>
<%= f.text_field :commenter %>
 </p>
<p>
<%= f.label :Comment %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>


</div><!--end left column-->
<div class="four wide column"><!--right column-->
  <p>
  Text
  </p>
  </div><!--end right column-->
  </div>
</div><!--End of main page container-->

enter image description here


Solution

  • A link in article should be html, not ruby. So it should be

    <a href='http://www.londoncoffestival.com'>London Coffee Festival</a>
    

    And change code in your template to

    <%== @article.text %>
    

    == is important here, it will tell rails to not escape html in text