【问题标题】:Showing images with Rails from database从数据库中显示带有 Rails 的图像
【发布时间】:2015-07-02 19:03:20
【问题描述】:

我正在尝试将我“存储”在数据库中的特定类型的图像显示到视图上。我有一个“产品”模型和一个“图像”模型,因为每个产品都有几种类型的图像(例如“图库”、“特色”、“拆箱图像”,它们简单地存储为类型 0 的属性, 1 或 2)

我已将其放入 HTML:

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

当我点击检查元素时,我看到了这个:

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

有人可以解释为什么会发生这种情况吗?看起来它正在我的资产/图像文件夹中搜索图像,但那里的 #

这是我的图像模型:

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

谢谢。

【问题讨论】:

  • 你能把你的图片模型发上来吗
  • 您是否尝试过预编译您的资产?
  • 你需要将一个url传递给image_tag的src..

标签: html ruby-on-rails database


【解决方案1】:

@product.images.where(image_type: 2).first 从数据库返回第一条记录,但对于 image_tag,您应该为返回的记录指定 urlpath

使用url 属性或您拥有的属性:

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

【讨论】:

  • 我试过这个,但加载时出现错误:undefined method `url' for #<0x007fcba3274928>
【解决方案2】:

发生了什么:image_tag 使用 object#to_s 方法返回模型标识

用来告诉你,这是一个对象

图像 - 对象类 0x007fcba329f4c0 - 对象实例的id

*_path 帮助器仅适用于控制器,因为它们是请求(浏览器)交互的对象。

我将创建一个单独的控制器 ImagesController 仅具有 #show 操作。然后在视图中显示图像(例如 )。然后 image_tag 将采用 image_path(@product.images.where(image_type: 2).first)。

只要确保您发送的是正确的 MIME 类型: http://api.rubyonrails.org/classes/Mime/Type.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2016-01-04
    • 2015-02-12
    • 1970-01-01
    • 2013-08-21
    相关资源
    最近更新 更多