使用 Rails 显示数据库中的图像 [英] Showing images with Rails from database
问题描述
我正在尝试将我存储"在数据库中的特定类型的图像显示到视图上.我有一个产品"模型和一个图像"模型,因为每个产品都有几种类型的图像(例如图库"、特色"、拆箱图像",它们被简单地存储为类型 0 的属性, 1 或 2)
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)
我已将其放入 HTML 中:
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>">
有人可以解释一下为什么会发生这种情况吗?看起来它正在我的资产/图像文件夹中搜索图像,但那是什么 #<和这样的在那里?我的图像在数据库中存储为像 lamp.png 一样.
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.
这是我的图像模型:
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
谢谢.
推荐答案
@product.images.where(image_type: 2).first
从数据库返回第一条记录,但对于 image_tag
你应该为返回的记录指定 url
或 path
.
@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.
使用 url
属性或您拥有的:
Use url
attribut or what you have:
<%= image_tag @product.images.where(image_type: 2).first.url, :alt => 'product_image' %>
^^^
这篇关于使用 Rails 显示数据库中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!