在rails,carrierwave和mongoid上传图像时出现问题

时间:2011-09-08 18:16:58

标签: ruby-on-rails ruby mongoid carrierwave

我在使用rails和carrierwave将图片上传到mongodb时遇到问题。这是我得到的错误消息

Cannot serialize an object of class ActionDispatch::Http::UploadedFile into BSON.

我的模型看起来像这样

class Offer
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, :type => String
  field :desc, :type => String
  field :expiry, :type => Date

   has_one :image, as: :viewable
  embeds_many :locations, as: :locatable
end

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

  field :name, :type => String
  field :extension, :type => String
  mount_uploader :image, ImageUploader

  belongs_to :viewable, polymorphic: true
end

视图是

<%= nested_form_for @offer, :html => {:method => :post, :id => "offerNew", :class => "uniForm", :multipart => true} do |f| %>

<fieldset class="inlineLabels" id="setBiz">
  <div class="ctrlHolder">
    <%= f.label :name, mark_mandatory("Offer Name") %>
    <%= f.text_field :name, :class => "textInput large" %>
    <p class="formHint">Name of the offer to be displayed in ads ex:5% offer on Panasonic vierra LCD </p>
  </div>

   <div class="ctrlHolder">
    <%= f.label :image, "Image" %>
    <%= f.file_field :image %>
    <p class="formHint">Upload image </p>
  </div>

</fieldset>
<% end %>

这些是发送到控制器的参数

"utf8"=>"✓",
 "authenticity_token"=>"8GhVGBg2zTI9FQwZmnKiZtBmgM5DiaQmPZaUIhNeF6I=",
 "offer"=>{"catid"=>"4e590231b356f8015f000030",
 "name"=>"aaaaaaaaaaaaaaaaaaaa",
 "expiry"=>"22/09/2011",
 "image"=>#<ActionDispatch::Http::UploadedFile:0xb412e30 @original_filename="51MF4101AA000.jpg",
 @content_type="image/jpeg",
 @headers="Content-Disposition: form-data; name=\"offer[image]\"; filename=\"51MF4101AA000.jpg\"\r\nContent-Type: image/jpeg\r\n",
 @tempfile=#<File:/tmp/RackMultipart20110908-2893-1a8yqe2>>,
 "loc"=>[80.22167450000006,
 13.0454044],
}}

但它在另一种形式下工作正常,我手动创建像这样的图像文件

params[:images].each do |img|
        image = Image.new(:extension => img.content_type.split('/')[1])
        image.image = img
        @business.images << image
end

我认为carrierwave会处理这个文件处理,但我不确定错过了什么?

2 个答案:

答案 0 :(得分:1)

问题是您需要更新由mount_uploader调用定义的:image属性,而不是更新调用mount_uploader的Image模型。换句话说,您需要更新Offer.image.image而不是Offer.image。

这应该有效:

   **** snip ****

   <div class="ctrlHolder">
    <%= f.fields_for Image.new do |i| %>
      <%= i.label :image, "Image" %>
      <%= i.file_field :image %>
    <%= end %>
    <p class="formHint">Upload image </p>
  </div>

  **** snip ****

答案 1 :(得分:0)

我必须承认我对nested_form_for不熟悉。此外,调试您的示例有点令人困惑,因为两个模型都有:name和:image as fields。

在我的例子中,一个Item有很多照片。在新视图中,我要求一个项目有一张照片。我认为那些fields_for可能会有所不同?

控制器:

@item = Item.new
@photo = @item.photos.build

查看:

<%= form_for(@item, :multipart=>true) do |f| %>
<h3>Photo</h3>
<div class="photo">
  <%= f.fields_for :photos do |ff| %>
  <%= ff.file_field :file %>
<% end %>
</div>
<% end %>