Reputation: 29
I have a two models, Items and Images. Under image model belongs_to :item and the item model has:many :images.
The image model has an item_id attribute.
Under the Items viewer I'm trying to display the images associated with each item. So for example I'd like to display image with item_id 1000 mapping onto Item with ID 1000.
I get a Couldn't find Image with an ID error.
The Viewer looks like this:
<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 %>
The Items Controller like this:
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
.
.
.
Help for a noob would be appreciated!
Upvotes: 1
Views: 1405
Reputation: 1124
So it seems like there is no image with params[:item_id]
You are using :item_id - thats right. Next you shoud use has_one :image in item.rb and belongs_to :item in image.rb. so your code will looks like:
def index
@items = Item.all
and in view
<td><%= image_tag item.image.small_img %></td>
UPD: enter rails console and ensure that all images has an item_id by:
Image.where(:item_id => nil)
UPD2: Do not use pgadmin with rails, rails - best database administration tool.
Upvotes: 1
Reputation: 47462
Change
@findimages = Image.find(params[:item_id])
To
@findimages = Image.find_by_id(params[:item_id])
Ref find
it states that If no record can be found for all of the listed ids, then RecordNotFound will be raised.
Where as find_by_id
it will return nil
when no record found for given id
Upvotes: 0