【问题标题】:how to render view/index in another view/index?如何在另一个视图/索引中呈现视图/索引?
【发布时间】:2017-03-31 00:27:09
【问题描述】:

我不明白如何将代码插入到我的 welcome/index.html.erb 文件中。这是我的代码:

Welcome_controller.rb

def index
  @welcomes = Welcome.all
end

Schedules_controller.rb

def index
  @schedules = Schedule.all
end

时间表/index.html.erb

          <table class="table table-hover">
            <thead>
              <tr>
                <th>Время<br>отправления</th>
                <th>Город</th>
                <th>Место<br> отправления</th>
                <th>Время <br>прибытия</th>
              </tr>
            </thead>
            <tbody>
            <% @schedules.each do |s| %>
              <tr>
                <td><%= s.deptime %></td>
                <td><%= s.city %></td>
                <td><%= s.street %></td>
                <td><%= s.aparttime %></td>
              </tr> 
            <% end %>             
            </tbody>
          </table>

如何将该代码插入welcome/index.html.erb?

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

用内容创建部分app/views/shared/_index_table.html.erb

<table class="table table-hover">
  <thead>
    <tr>
      <th>Время<br>отправления</th>
      <th>Город</th>
      <th>Место<br> отправления</th>
      <th>Время <br>прибытия</th>
    </tr>
  </thead>
  <tbody>
  <% schedules.each do |s| %>
    <tr>
      <td><%= s.deptime %></td>
      <td><%= s.city %></td>
      <td><%= s.street %></td>
      <td><%= s.aparttime %></td>
    </tr> 
  <% end %>             
  </tbody>
</table>

那么,app/views/schedules/index.html.erb

<h1>Schedules</h1>
<%= render partial: "shared/index_table", :locals => { schedules: @welcomes } %>

app/views/welcomes/index.html.erb

<h1>Welcome</h1>
<%= render partial: "shared/index_table", :locals => { schedules: @schedules } %>

仅当您在 WelcomeSchedule 模型上具有相同的属性集(deptime、city、street、parttime)时,这才有效

【讨论】:

    【解决方案2】:

    从 welcomes_controller.rb 中渲染时间表索引模板

    def index
      @welcomes = Welcome.all
      render "/schedules/index"
    end
    

    但是,这会带来一个问题,因为视图中的表依赖于要设置的 @schedules 实例变量,并且它将返回 nil,因为它没有在控制器中分配值。

    你可能想这样做:

    def index
      @schedules = Welcome.all
      render "/schedules/index"
    end
    

    从语义的角度来看,这对我来说并没有什么意义。您可能希望将实例变量重命名为与模型无关的名称。

    在另一个答案中,建议使用部分。这实际上可能是一个更好的解决方案,具体取决于用例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-24
      • 2016-11-03
      • 2014-02-09
      • 1970-01-01
      • 2019-03-31
      • 2011-01-13
      • 2013-04-12
      • 1970-01-01
      相关资源
      最近更新 更多