0

モデルのインデックスページで奇妙な動作が発生します。モデルオブジェクトを1つ作成すると、インデックスページに正しく表示されます。2番目のモデルオブジェクトを作成すると、インデックスページに両方のオブジェクトの複製が表示されます。

OBJECT A
OBJECT B
OBJECT A
OBJECT B

データベースに重複オブジェクトが作成されていないことを確認しました。また、オブジェクトBを破棄すると、オブジェクトAが正しく表示されるのは1回だけです。

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
4

2 に答える 2

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 %>パーシャルをレンダリングしますが、各パーシャルで再び会社をループしています。

詳細については、http: //guides.rubyonrails.org/layouts_and_rendering.html#rendering-collectionsの3.4.5レンダリングコレクションを参照してください。

于 2013-03-24T20:52:01.257 に答える
1

<%= render @companies %><%= render "company" %>;に変更します。パーシャルは会社ごとに1つずつ、複数回レンダリングされており、パーシャルはすべての会社をレンダリングしています。これは部分的なものだけをレンダリングし、すべての会社をレンダリングします。これはあなたが望むものです。

于 2013-03-24T20:54:54.473 に答える