2013-03-24 21 views
0

我的模型索引頁面上出現一些奇怪的行爲。當我創建一個模型對象時,它在索引頁面上正確顯示。當我創建第二個模型對象,它顯示的索引頁面上兩個對象的副本,像這樣模型index.html頁面顯示重複的數據

OBJECT A 
OBJECT B 
OBJECT A 
OBJECT B 

未在我的數據庫中創建重複的對象,我證實。另外,當我銷燬OBJECT B時,它只能正確顯示OBJECT A一次。

index.html.erb

<table class="table"> 
    <thead> 
    <tr> 
     <th>Image</th> 
     <th>Name</th> 
     <th>Description</th> 
     <th>URL</th> 
     <th></th> 
     <th></th> 
     <th></th> 
    </tr> 
    </thead> 

    <tbody> 
    <%= render @companies %> 
    </tbody> 
</table> 

_company.html.erb

<% @companies.each do |company| %> 
    <tr> 
    <td><%= image_tag company.image(:medium) %></td> 
    <td><%= company.name %></td> 
    <td><%= company.description %></td> 
    <td><%= company.url %></td> 
    <td><%= link_to 'Show', company %></td> 
    <td><%= link_to 'Edit', edit_company_path(company) %></td> 
    <td><%= link_to 'Destroy', company, method: :delete, data: { confirm: 'Are you sure?' } %></td> 
    </tr> 
<% end %> 

companies_controller.rb

def index 
    @companies = Company.all 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @companies } 
    end 
    end 
+0

這裏鏈接的部分名稱是什麼? – drewinglis 2013-03-24 20:48:10

+0

_company.html.erb – mnort9 2013-03-24 20:52:09

+0

請將您的控制器代碼發佈到'index'動作。也可以在你的例子中修剪HTML; ''這幾行在這裏並不重要。 – 2013-03-24 20:52:30

回答

2

更改您的偏,

<tr> 
    <td><%= image_tag company.image(:medium) %></td> 
    <td><%= company.name %></td> 
    <td><%= company.description %></td> 
    <td><%= company.url %></td> 
    <td><%= link_to 'Show', company %></td> 
    <td><%= link_to 'Edit', edit_company_path(company) %></td> 
    <td><%= link_to 'Destroy', company, method: :delete, data: { confirm: 'Are you sure?' } %></td> 
</tr> 

你需要放棄你的部分中的每個循環。

<%= render @companies %>呈現每個公司的部分,但你也在每個部分再次循環公司。

3.4.5渲染集合http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-collections更多信息

1

更改<%= render @companies %><%= render "company" %>;你的部分被渲染多次,每個公司一個,你的部分渲染所有的公司。這隻會渲染部分,這將使所有的公司,這是你想要的。

相關問題