I have a posts model… I am trying to display this model on the index page of the webpage.
<% @posts.each do |post| %>
<%= @posts[1].title %>
<%end%>
The problem with the above code is that it display the title 3 times because i have 3 posts. How do i edit this code to make it only display once.
You meant to do this:
The
eachenumerator passes its variables one at a time into a block with thedo |variable|syntax. Sopostis each item in@posts, one after another.This is a really fundamental concept to Ruby and Rails: without understanding this further you probably won’t get very far. I would recommend you go and read Programming Ruby — a really excellent tutorial and reference to the Ruby programming language — to understand how blocks and enumerators work.