[英]how to render view/index in another view/index?
我不明白如何將代碼插入到welcome / index.html.erb文件中。 這是我的代碼:
def index
@welcomes = Welcome.all
end
def index
@schedules = Schedule.all
end
<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?
使用內容創建部分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 } %>
僅當您在Welcome
和Schedule
模型上具有相同的屬性集(deptime,city,street,aparttime)時,此方法才有效
從welcome_controller.rb呈現計划索引模板
def index
@welcomes = Welcome.all
render "/schedules/index"
end
但是,這會出現問題,因為視圖中的表依賴於要設置的@schedules
實例變量,並且它將返回nil
因為它未在控制器中分配值。
你可能想這樣做:
def index
@schedules = Welcome.all
render "/schedules/index"
end
從語義的角度來看,這對我來說並沒有多大意義。 您可能希望將實例變量重命名為更加模型不可知的東西。
在另一個答案中,建議使用部分。 根據用例,這實際上可能是更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.