2

我想包圍我的頭使用多態關聯,使文件管理在一個簡單的軌道應用程序重複性較低。我正在使用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' 

回答

6

後參數應該是這樣的

params => { "photo" => 
       { :attachment_attribute => 
        {:file => ActionDispatch::Http::UploadedFile} 
       } 
      } 

但您的帖子PARAM最有可能是

params => { "photo" => { :attachment => ActionDispatch::Http::UploadedFile}} 

你的觀點應該包含fields_for來處理模型嵌套。你必須創建一個文件場的附件模型的屬性 「文件」

<%=form_for @photo do |photo_f|%> 
    .... 
    <%=photo_f.fields_for :attachment do |attachment_f|%> 
    <%= attachment_f.file_field :file%> 
    <%end%> 
    .... 
<%end%> 

UPDATE

<%=photo_f.fields_for :attachment_attributes do |attachment_f|%> 

而在照片模式中添加這些,

accepts_nested_attributes_for :attachment 
attr_accessible ..., :attachment_attributes 
+0

感謝幫助@manoj。我覺得我越來越近了,但我得到了上述錯誤(請參閱我的問題的更新) – Tyler

+0

幫助我的是ANAF的東西。感謝慢跑我的記憶! – thekingoftruth

0
<%=form_for @photo do |photo_f|%> 
.... 
<%=photo_f.fields_for :attachment_attributes do |attachment_f|%> 
    <%= attachment_f.file_field :file %> 
<%end%> 
.... 
<%end%> 
+0

謹慎解釋? – shivam