我正试图在一个简单的rails应用程序中使用多态关联来减少文件管理的重复性。我正在使用carrierwave来处理文件上传。以下是到目前为止我所拥有的:
应用程序/上传程序/文件上传程序.rb
class FileUploader < CarrierWave::Uploader::Base
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
应用程序/模型/附件.rb
class Attachment < ActiveRecord::Base
mount_uploader :file, FileUploader
belongs_to :attachable, polymorphic: true
end
应用程序/模型/照片.rb
class Photo < ActiveRecord::Base
attr_accessible :caption, :attachment
has_one :attachment, as: :attachable
end
我可以在rails控制台中处理此罚款:
$ rails console
> photo = Photo.new
> attachment = Attachment.new
> attachment.file = File.open('tmp/demo.png')
> photo.attachment = attachment
> photo.save
> photo.attachment
=> #<Attachment id: 3, file: "demo.png", attachable_id: 5, attachable_type: "Photo", created_at: "2013-04-13 16:56:31", updated_at: "2013-04-13 16:56:31">
所以我的问题实际上在于照片控制器:
ActiveRecord::AssociationTypeMismatch in PhotosController#create
Attachment(#70310274945400) expected, got ActionDispatch::Http::UploadedFile(#70310271741380)`
我们非常感谢在这方面的任何帮助。我可能对多态性关联没有最深入的了解。
更新
根据@manoj的建议,我编辑了照片表单以嵌套附件:
<%= f.fields_for :attachment do |attachment_f| %>
<%= attachment_f.file_field :file %>
<% end %>
我现在在尝试提交表单时遇到此错误:
ActiveRecord::AssociationTypeMismatch (Attachment(#70135925415240) expected, got ActiveSupport::HashWithIndifferentAccess(#70135923190420)):
app/controllers/photos_controller.rb:43:in 'new'
app/controllers/photos_controller.rb:43:in 'create'