0

I am doing the Jumpstart tutorial where you have to create a blog in ruby on rails. It is going fine but I have not managed to figure out one thing. The root page is supposed to show a list of articles. And it does. Only it also shows this extra bit: Article list and unwanted part at the bottom

The code I have in the view:

<h1> All Articles </h1>


<ul id="articles">
    <%= @articles.each do |article| %>
        <li>
            <%= link_to article.title, article_path(article), class: 'article_title' %>
        </li>
    <% end %>
</ul>

<%= link_to "Create New Article", new_article_path, class: 'new_article' %>

And here is the relevant code in the controller

def index
    @articles = Article.all
end

I would appreciate any help on why this is happening.

3 Answers3

1

Take out the = sign of your loop So: <% @articles.each do |article| %>

RuNpiXelruN
  • 1,850
  • 2
  • 17
  • 23
0

In Embedded Ruby (ERB), the difference between <% %> and <%= %> is not simply cosmetic; the latter actually prints the results of the line of code into the html. As such, in your line:

<%= @articles.each do |article| %>

...You are actually printing the results of running that line of code and displaying it. Or, more specifically, you're displaying loop itself, not just the results of looping through the @articles collection. You'll get a lot of gibberish from haphazardly using the <%= %> notation. Just look at when you play around in the console/debugger; running these lines of code makes a lot of noise!

To fix your problem, your loop through @articles should simply look like this:

# No "=" here!
<% @articles.each do |article| %>
    <li>
        <%= link_to article.title, article_path(article), class: 'article_title' %>
    </li>
<% end %>

For more information on ERB syntax, look here.

For another stack overflow question encompassing this and a few additional notation, look here.

Community
  • 1
  • 1
ConnorCMcKee
  • 1,625
  • 1
  • 11
  • 23
0
<% @articles.each do |article| %>
   <%= content_tag :li, link_to(article.title, article, class: 'article_title') %>
<% end %>

Struggled with the same issue for 2 days when starting.

Richard Peck
  • 76,116
  • 9
  • 93
  • 147