Skip to content Skip to sidebar Skip to footer

Showing Images With Rails From Database

I'm trying to show a specific type of image that I've 'stored' in the database onto the view. I have a model for 'products' and a model for 'images' as I have several types of imag

Solution 1:

@product.images.where(image_type: 2).first returns a first record from database, but for image_tag you should specify url or path for returned records.

Use url attribut or what you have:

<%= image_tag @product.images.where(image_type: 2).first.url, :alt => 'product_image' %>
                                                         ^^^

Solution 2:

What is happening: image_tag uses object#to_s method which returns the model identyfication

<> is used to tell you, that this is an object

Image - class of object 0x007fcba329f4c0 - id of object instance

The *_path helper is avalible for controllers only, as they are the ones the request (browser) interacts is.

I'd create a separate controller ImagesController with only #show action. Then display the image in the view (eg <%= @image.data %>). Then the image_tag would take image_path(@product.images.where(image_type: 2).first).

Just make sure, that you are sending the correct MIME type: http://api.rubyonrails.org/classes/Mime/Type.html

Post a Comment for "Showing Images With Rails From Database"