【问题标题】:Undefined Method 'metadata' when uploading using mongoid-paperclip gem使用 mongoid-paperclip gem 上传时未定义的方法“元数据”
【发布时间】:2011-06-10 21:45:04
【问题描述】:

在尝试使用 Mongoid 和 Paperclip 上传文件时,我不知道为什么会出现此问题。

undefined method `metadata' for #<ActionDispatch::Http::UploadedFile:0x10625e930>

我正在运行以下命令(最新的回形针、mongoid-paperclip 和 aws-s3):

gem "rails", "3.0.6"
gem "mongoid", "2.0.1"
gem "bson_ext", "1.3.0"
gem "paperclip"
gem "mongoid-paperclip", :require => "mongoid_paperclip"
gem "aws-s3",            :require => "aws/s3"

我看到一些地方建议将以下内容添加到初始化程序中,以处理看起来相似的事情。我已经这样做了,但无济于事。

if defined? ActionDispatch::Http::UploadedFile
    ActionDispatch::Http::UploadedFile.send(:include, Paperclip::Upfile)
end

还有其他人遇到过这种情况吗?

【问题讨论】:

  • 我不断得到这个并解决它(但使用carrierwave),但我不记得如何。您能否向我们展示您正在保存图像的模型以及从中上传图像的表单。漂亮请。

标签: ruby-on-rails-3 paperclip mongoid


【解决方案1】:

我有上传者:

class Image
  include Mongoid::Document
  embedded_in :imageable, polymorphic: true
  mount_uploader :file, ImageUploader
end

在我所有包含图片的类中都用到了,比如:

class Shop
  include Mongoid::Document
  embeds_one :logo, as: :imageable, :class_name => 'Image', cascade_callbacks: true  
end

那么在表格中是这样的:

<%= form_for @shop do |f| %>
  <%= f.fields_for :cover do |u|%>
    <%= u.file_field :file %>
  <% end %>
  <%= f.submit 'Save' %>
<% end %>

我认为这是处理问题的一种非常巧妙的方法。

【讨论】:

  • 不应该是&lt;%= f.fields_for :logo do |u|%&gt;吗?
【解决方案2】:

如上所述,我在使用 Mongoid、Carrierwave 和 GridFS 时遇到了类似的问题。
我的解决方案非常老套,但它对我有用。
我有一个 Image 类,这是我的图像的安装位置

class Image
  include Mongoid::Document
  include Mongoid::Timestamps

  field :title
  field :image
  field :order

  mount_uploader :image, ImageUploader
  embedded_in :article
end

class Article
  include Mongoid::Document
  ...
  embeds_one :image
  ...
end

我的carrierwave 上传器希望使用装载上传器的密钥将属性发送给它(图片)。

Image.create( :image => image_attributes)

但是文章的新/编辑表单创建的内容看起来像:

:article => { :image => #ActionDispatch... }

而不是

:article => { :image => { :image => #ActionDispatch... } }

所以我的解决方案是将表单中的字段名称更改为

file_field :article, :photo

然后将照片设置器添加到创建图像的文章类中

model Article
  include Mongoid::Document
  ...
  def photo=(attrs)
    create_image(:image => attrs)
  end
end

我用 image= 尝试过这个,但它无限递归并做了坏事。
我也试过这个

file_field "article[image]", :image

没有设置器,它没有引发异常,但也没有保存我的图像。

据我所知,回形针在这些方面非常相似。也许这对某人有用,或者有人可以收拾我的烂摊子

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2012-02-06
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    相关资源
    最近更新 更多