【问题标题】:Stuck completing my first rails app坚持完成我的第一个 Rails 应用程序
【发布时间】:2013-09-15 21:49:28
【问题描述】:

我在rails 上在线使用tutorial,但我被卡住了。这些是我的控制器和视图文件:

/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>

我需要更改代码#todo item here 以显示数组中的实际待办事项。所以我得到的输出为:

Shared Todo App

All your todos here

 - Buy Milk 
 - Buy Soap
 - Pay bill
 - Draw Money

【问题讨论】:

  • &lt;% @todo_array.each do |t| %&gt; &lt;li&gt; &lt;%= t %&gt; &lt;/li&gt; &lt;% end %&gt;

标签: ruby-on-rails actionview actioncontroller


【解决方案1】:
<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>

但是由于您在这部分上遇到了困难,我建议您从不同的教程或书籍开始,这些内容可以更多地解释您正在做什么以及为什么。 http://ruby.railstutorial.org/ruby-on-rails-tutorial-book

【讨论】:

    【解决方案2】:

    控制器中的实例变量在视图中作为实例变量传递。

    控制器:

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

    查看:

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

    【讨论】:

      【解决方案3】:

      只需将评论替换为&lt;%= t %&gt;。 Rails 会自动显示数组的每个值:

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

      【讨论】:

        【解决方案4】:

        根据教程和小红宝石演示,有人提到 使用块访问数组的每个元素。 arr.each { |a| puts a } 打印数组的所有元素。

        但是,您只需通过 &lt;%= t %&gt; 来代替评论。

        所以你的最后一段代码将是:

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

        【讨论】:

          猜你喜欢
          相关资源
          最近更新 更多
          热门标签