1

アイテムと画像の2つのモデルがあります。画像モデルの下にbelongs_to:itemがあり、アイテムモデルには:many:imagesがあります。

画像モデルにはitem_id属性があります。

アイテムビューアの下に、各アイテムに関連付けられている画像を表示しようとしています。たとえば、item_id1000の画像をID1000のItemにマッピングして表示したいとします。

IDエラーのある画像が見つかりませんでした。

ビューアは次のようになります。

<h1>Listing items - temporary testing page</h1>

<table>
  <tr>
    <th>Brand</th>
    <th>Item title</th>
    <th>Description</th>
    <th>Image link</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @items.each do |item| %>
  <tr>
    <td><%= item.brand %></td>
    <td><%= item.item_title %></td>
    <td><%= item.description %></td>
    <td><%= item.image_id %></td>
    <td><%= image_tag @findimages.small_img %></td>
    <td><%= link_to 'Show', item %></td>
    <td><%= link_to 'Edit', edit_item_path(item) %></td>
    <td><%= link_to 'Destroy', item, method: :delete, data: { confirm: 'Are you sure?' }     %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New Item', new_item_path %>

このようなアイテムコントローラー:

class ItemsController < ApplicationController
  # GET /items
  # GET /items.json
  def index
    @items = Item.all(params[:id])
    @findimages = Image.find(params[:item_id])

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

初心者のための助けをいただければ幸いです!

4

2 に答える 2

1

したがって、params [:item_id]を含む画像がないようです。

  1. @findimages = Image.find(params [:item_id])if params [:item_id]を使用します
  2. image.rbでvalidates_presence_of:item_idを使用します
  3. Item.all(params [:id])-
    Item.allの間違ったItem.find(params [:id])
  4. :item_idを使用しています-その通りです。次に、item.rbのhas_one:imageとimage.rbのbelongs_to:itemを使用する必要があります。したがって、コードは次のようになります。

    def index  
      @items = Item.all
    

とビューで

<td><%= image_tag item.image.small_img %></td>

UPD:Rails Consoleに入り、すべての画像にitem_idが含まれていることを確認します。

Image.where(:item_id => nil)

UPD2:pgadminをrails、railsと一緒に使用しないでください-最高のデータベース管理ツールです。

于 2012-10-16T10:45:20.467 に答える
0

変化する

@findimages = Image.find(params[:item_id])

@findimages = Image.find_by_id(params[:item_id])

Reffindそれは次のように述べていますIf no record can be found for all of the listed ids, then RecordNotFound will be raised.

指定されたIDのレコードが見つからない場合find_by_idに返される場所nil

于 2012-10-16T10:21:46.430 に答える