【发布时间】:2011-10-23 14:34:53
【问题描述】:
我正在关注GridFS with Mongoid and CarrierWave 来实现一个简单的 has_many 多态关系,当我尝试通过嵌套属性分配创建一个具有头像的新用户时,我得到:
Cannot serialize an object of class ActionDispatch::Http::UploadedFile into BSON
有没有其他人遇到过这种情况?我注意到一些人回复了“GridFS with Mongoid and CarrierWave”一文,但我找不到任何人提供答案。
# app/models/asset.rb
class Asset
include Mongoid::Document
include Mongoid::Timestamps
mount_uploader :file, AssetUploader
field :name, type: String
referenced_in :attachable, polymorphic: true
end
# app/models/user.rb
class User
include Mongoid::Document
include Mongoid::Timestamps
references_one :avatar, as: :attachable
accepts_nested_attributes :avatar
end
# config/initializers/carrierwave.rb
CarrierWave.configure do |config|
config.grid_fs_connection = Mongoid.database
config.storage = :grid_fs
config.grid_fs_access_url = "/images"
end
# app/uploaders/asset_uploader.rb
class AssetUploader < CarrierWave::Uploader::Base
end
# app/views/users/new.html.haml
= semantic_form_for(@user, html: { multipart: true }) do |f|
= f.inputs do
= f.semantic_fields_for :avatar do |af|
= af.input :file, as: :file
= f.buttons do
= f.commit_button "Upload"
【问题讨论】:
-
如果您遇到这种情况,请确保您已正确命名表单字段。上面的代码工作得很好,假设没有不匹配的输入字段名称和关联名称。
标签: mongoid carrierwave gridfs