视图中的 textNode 来自哪里?

Where's the textNode in the view coming from?

# controller
def index
  @teams = TeamMember.where(user: current_user)
end
# view
<%= @teams.each do |t| %>
  <h2><%= t.project.name %></h2>
  <p>Where's the line below this coming from?</p>
  <!-- what's happening here? -->
<% end %>

浏览器中的结果如下所示。它 returns @projects 作为一个字符串。这是从哪里来的,我该如何删除它?

ERB

You trigger ERB by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output.

您已将 <%= %> 用于循环项目和 Array#each returns 原始 Array object 的块形式,这就是它在最后打印项目结果的原因.

你必须为 @projects.each do |p| 使用 <% %> 而不是 <%= %>

# view
<% @projects.each do |p| %>
  <h2><%= p.name %></h2>
<% end %>

团队成员模型

 class TeamMember < ApplicationRecord
    
    belongs_to :user
    belongs_to :project

 end

用户模型

 class User < ApplicationRecord

    has_many :team_members

 end

项目模型

 class Project < ApplicationRecord

    has_many :team_members

 end

控制器

def index
  @teams = current_user.team_members
end

查看

<% @teams.each do |t| %> // Remove '=' from the loop itereation
  <h2> <%= t.project.name %> </h2>
<% end %>