我正在尝试使用多态关联来减少文件管理在简单的 Rails 应用程序中的重复性。我正在使用carrierwave来处理文件上传。这是我到目前为止所拥有的:
应用程序/上传程序/file_uploader.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
应用程序/模型/photo.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'