代码之家  ›  专栏  ›  技术社区  ›  Martin Greenaway

RubyonRails:为什么当我遍历每个孩子时,他们的内容都会打印出来?

  •  0
  • Martin Greenaway  · 技术社区  · 9 年前

    我有以下型号:

    class Question < ActiveRecord::Base
        has_many :ratings
    end
    
    class Rating < ActiveRecord::Base
      belongs_to :question
    end
    

    我在问题的show.html中也有以下代码。erb文件:

    <p id="notice"><%= notice %></p>
    
    <p>
      <strong>Name:</strong>
      <%= @question.name %>
    </p>
    
    <% if @ratings.blank? %>
        <p>There are no ratings for this question.</p>
    <% else %>
        <ul>
            <%= @ratings.each do |rating| %>
                <li>
                    <%= rating.name %>
                    <%= link_to "Show", rating %>
                </li>
            <% end %>
        </ul>
    <% end %>
    <%= link_to 'Edit', edit_question_path(@question) %> |
    <%= link_to 'Back', questions_path %>
    

    相关问题_控制器。rb条目如下:

    def show
      @question = Question.find(params[:id])
      @ratings = Rating.where(question_id: @question.id)
      respond_with(@question)
    end
    

    我一辈子都不明白为什么输出包含子对象的内容,以及我在迭代中创建的无序列表项。有什么想法吗?

    Screenshot

    2 回复  |  直到 8 年前
        1
  •  4
  •   bumpy    9 年前

    尝试删除 = 在这一行中: <%= @ratings.each do |rating| %>

        2
  •  -1
  •   crazy_phage    9 年前

    在每个循环中使用-but=

    - @pages.each do |x|
     p = x.id
     p = x.xx
    

    这就是你想要的。

    此外,我建议您使用slim代替erb。