【发布时间】:2020-01-19 02:57:06
【问题描述】:
我正在尝试使用 rails_admin gem 在记录行中显示我保存在 Mongo 中的图像。
我有我的模型保存和我的图像保存,我正在将图像 ID 保存在模型记录中。
这是我的模型:
require 'mongoid/grid_fs'
class Asset
include Mongoid::Document
field :data_file_name, type: String
field :data_content_type, type: String
field :data_file_size, type: Integer
field :image_id, type: String
end
这是我在 rails_admin.rb 中为我的资产模型所做的事情:
list do
field :id
field :data_file_name
field :data_content_type
field :data_file_size
field :image do
formatted_value do
grid_fs = Mongoid::GridFs
bindings[:view].tag(:img, { :src => grid_fs.get(bindings[:object].image_id)})
end
end
end
这是负责保存模型和图像的操作:
register_instance_option :controller do
proc do
if request.get? # EDIT
respond_to do |format|
format.html { render @action.template_name }
format.js { render @action.template_name, layout: false }
end
elsif request.put? # UPDATE
tempFile = params[:picture][:asset].tempfile
file = File.open(tempFile)
grid_fs = Mongoid::GridFS
grid_file = grid_fs.put(file.path)
Asset.new.tap do |asset|
asset.data_file_name = params[:picture][:asset].original_filename
asset.data_content_type = params[:picture][:asset].content_type
asset.data_file_size = ::ApplicationController.helpers.number_to_human_size(File.size(tempFile))
asset.image_id = grid_file.id
asset.save
binding.pry
end
end
end
end
模型正在保存,我可以在 fs.files 和 fs.chunks 中看到文件保存,但目前,我只是在记录行中得到以下内容:
更新:
我现在尝试从 mongo 获取文件(这似乎可行),然后使用文件的实际文件名显示图像。
field :image do
formatted_value do
grid_fs = Mongoid::GridFs
f = grid_fs.get(bindings[:object].image_id)
bindings[:view].tag(:img, { :src => f.filename})
end
end
不幸的是,这并没有改变任何东西。尝试在新选项卡中打开图像会将我带到以下链接:/admin/asset#<Mongoid::GridFs::Fs::File:0x981vj5ry>
更新 2:
将field :image_id, type: String 更改为field :image_id, type: BSON::ObjectId
结果没有变化。
【问题讨论】:
标签: ruby-on-rails mongoid gridfs rails-admin