Kumo
Kumo

Reputation: 189

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 images for each product (such as "gallery", "featured", "unboxing image" which are simplely stored as an attribute of type 0, 1 or 2)

I've put this into the HTML:

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

When I click to inspect element, I see this:

<img alt="product_image" src="/images/#<Image:0x007fcba329f4c0>">

Can someone please explain why what is happening? It looks like it is searching for the image in my assets/images folder but what is that #< and such in there? My image is stored as like lamp.png in the database.

This is my Image model:

class Image < ActiveRecord::Base

  include AASM

  belongs_to :product
  mount_uploader :file, FileUploader

  validates :image_type, presence: true


  enum image_type: [IMAGE_UNBOXING.to_s, IMAGE_GALLERY.to_s, IMAGE_FEATURED.to_s]

  aasm column: :image_type do
    Image.image_types.keys.each do |state_string|
      state state_string.to_sym
    end

  end

end

Thank you.

Upvotes: 2

Views: 2923

Answers (2)

Michal
Michal

Reputation: 753

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

Upvotes: 1

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

@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' %>
                                                         ^^^

Upvotes: 3

Related Questions