我有多個模型,他們的索引視圖幾乎共享完全相同的代碼和佈局。如何與多個模型共享相同的視圖?
... /巧克力/ index.html.erb
<h1 class="col-sm-12 head">Index Bases</h1>
<hr>
<% @chocolates.each do |chocolate| %>
<%= link_to chocolate do %>
<%= set_img(chocolate) %>
<% end %>
<ul>
<li><%= chocolate.name %></li>
<li><%= chocolate.position %></li>
</ul>
<hr>
<div>
<%= link_to chocolate do %>
<span class="glyphicon glyphicon-eye-open"></span>
<% end %>
<%= link_to edit_chocolate_path(chocolate) do %>
<span class="glyphicon glyphicon-edit"></span>
<% end %>
<%= link_to basis, method: :delete, data: { confirm: 'Are you sure?' } do %>
<span class="glyphicon glyphicon-remove"></span>
<% end %>
</div>
<% end %>
<hr>
<%= link_to '+ Add New Chocolate', new_chocolate_path %>
... /糕點/ index.html.erb
<h1 class="col-sm-12 head">Index Bases</h1>
<hr>
<% @sweets.each do |sweet| %>
<%= link_to sweet do %>
<%= set_img(sweet) %>
<% end %>
<ul>
<li><%= sweet.name %></li>
<li><%= sweet.position %></li>
</ul>
<hr>
<div>
<%= link_to sweet do %>
<span class="glyphicon glyphicon-eye-open"></span>
<% end %>
<%= link_to edit_sweet_path(sweet) do %>
<span class="glyphicon glyphicon-edit"></span>
<% end %>
<%= link_to sweet, method: :delete, data: { confirm: 'Are you sure?' } do %>
<span class="glyphicon glyphicon-remove"></span>
<% end %>
</div>
<% end %>
<hr>
<%= link_to '+ Add New Sweet', new_sweet_path %>
還有更多的模式,共享相同的佈局,我認爲我不斷重複我的自我,所以我創建了一個共享部分,並在每個使用該佈局的視圖中呈現變量。
... /糕點/ index.html.erb
<% render 'shared/indexGrid', dist: @sweets%>
... /視圖/共享/ _indexGrid.html.erb
<% title = dist.class.name.underscore.tr('_', ' ').pluralize.split.map(&:capitalize).join(' ') %>
<% sing = dist.class.name.underscore %>
<h1>Index <% title %></h1>
<hr>
<% dist.each do |sing| %>
<%= link_to sing do %>
<%= set_img(sing) %>
<% end %>
<ul>
<li><%= sing.name %></li>
<li><%= sing.position %></li>
</ul>
<hr>
<div>
<%= link_to sing do %>
<span class="glyphicon glyphicon-eye-open"></span>
<% end %>
<%= link_to send("edit_#{sing.class.name.underscore}_path", sing) do %>
<span class="glyphicon glyphicon-edit"></span>
<% end %>
<%= link_to sing, class: 'square red', method: :delete, data: { confirm: 'Are you sure?' } do %>
<span class="glyphicon glyphicon-remove"></span>
<% end %>
</div>
<% end %>
<hr>
<%= link_to "+ Add New #{title}", send("new_#{sing.class.name.underscore}_path"), { class: 'btn btn-success btn-block'} %>
,但它沒」噸似乎工作,因爲 - 我認爲 - dist.class.name
deasnt返回我期待的價值,但返回"active_record/relation"
。 我已經嘗試過與編輯視圖相同的方法,它與dist: @sweet
。
我曾經想過使用佈局,但它給我留下了與其他索引視圖非常相似的大塊代碼。
我分享我嘗試用你的時候,這個問題......
- 這有什麼錯我的代碼,以及如何解決它?
- 該方法是否被認爲是DRY代碼的良好實踐?如果不是的話當這些模型幾乎共享完全相同的代碼和佈局時,與多個模型共享相同視圖代碼的最佳方式是什麼?
感謝男人的偉大答案,現在工作得很好,但我的第二部分問題仍然沒有答案,那麼你認爲這是做這種事情的最好方法嗎?你認爲在模型之間分享觀點是正確的 - 性能明智的或如此。我在查看'Partial'文檔,並且發現了一些名爲'collection'的東西,我懷疑這與這種情況有關。還有,當我運行'@ sweets.model_name'時,它返回了一個包含很多值的散列,如命名的路徑和其他實例變量我也懷疑它可以幫助。 –
增加了一些更多的信息,這將有助於... – Doon
謝謝你的男人,最後一段很有幫助 –