Pregunta

I was taking a tutorial online on rails but I got stuck. These are my controller and view files:

/app/controllers/todos_controller.rb:

class TodosController < ApplicationController
  def index
  @todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ]

  end
end

/app/views/todos/index.html.erb:

<title>Shared Todo App </title>
<h1>Shared Todo App</h1>
<p>All your todos here</p>
<ul>
  <% @todo_array.each do |t| %>
   <li> #todo item here </li>
   <% end %>
</ul>

I need to change the code #todo item here to show the actual todo item from the array. So I get output as:

Shared Todo App

All your todos here

 - Buy Milk 
 - Buy Soap
 - Pay bill
 - Draw Money
¿Fue útil?

Solución

<title>Shared Todo App </title>
<h1>Shared Todo App</h1>
<p>All your todos here</p>
<ul>
  <% @todo_array.each do |t| %>
    <li> <% t %> </li>
  <% end %>
</ul>

But since you're getting stuck on that part, I suggest you start with a different tutorial or book, something that explains a bit more about what you're doing and why. http://ruby.railstutorial.org/ruby-on-rails-tutorial-book

Otros consejos

Instance variables in your controller are passed as instance variables in your view.

Controller:

@todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ]

View:

<% @todo_array.each do |t| %>
   <li> <%= t %> </li>
   <% end %>

Just replace the comment by <%= t %>. Rails will automatically display each value of the array :

<% @todo_array.each do |t| %>
    <li><%= t %></li>
<% end %>

As per the tutorial and the little ruby demo it was mentioned that Accessing each element of array using blocks. arr.each { |a| puts a } prints all the elements of the array.

However you need to just pass <%= t %> in place of comment.

So your final piece of code will be:

  <% @todo_array.each do |t| %>
    <li> <%= t %> </li>
  <% end %>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top