我想包圍我的頭使用多態關聯,使文件管理在一個簡單的軌道應用程序重複性較低。我正在使用carrierwave處理文件上傳。這是我到目前爲止有:Rails上傳與載波和多態關聯的表格
應用程序/上傳/ file_uploader.rb
class FileUploader < CarrierWave::Uploader::Base
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
應用程序/模型/ attachment.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 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)`
任何的幫助是巨大的讚賞。我可能沒有掌握多態關聯。
UPDATE
以@馬諾的建議下,我編輯了照片的形式嵌套附件:
<%= 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'
感謝幫助@manoj。我覺得我越來越近了,但我得到了上述錯誤(請參閱我的問題的更新) – Tyler
幫助我的是ANAF的東西。感謝慢跑我的記憶! – thekingoftruth