【问题标题】:Where's the textNode in the view coming from?视图中的 textNode 来自哪里?
【发布时间】:2021-04-10 03:11:19
【问题描述】:

# 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 %>

浏览器中的结果如下所示。它以字符串形式返回@projects。这是从哪里来的,我该如何删除它?

【问题讨论】:

    标签: ruby-on-rails debugging model-view-controller


    【解决方案1】:

    团队成员模型

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

    【讨论】:

      【解决方案2】:

      ERB

      您可以使用 、 和 等嵌入来触发 ERB。 标签集在您想要输出时使用。

      您使用&lt;%= %&gt; 循环项目并且Array#each 的块形式返回原始Array object,这就是它在最后打印项目结果的原因。

      你必须使用&lt;% %&gt; 代替@projects.each do |p| 而不是&lt;%= %&gt;

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

      【讨论】:

        猜你喜欢
        • 2020-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-21
        • 1970-01-01
        • 2014-04-24
        • 2015-07-13
        • 1970-01-01
        相关资源
        最近更新 更多