Rails上传表单,包含carrierwave和多态关联

时间:2013-04-13 17:07:50

标签: ruby-on-rails ruby-on-rails-3 polymorphism carrierwave polymorphic-associations

我正试图利用多态关联来改变文件管理在一个简单的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

应用/模型/ attachment.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'

2 个答案:

答案 0 :(得分:6)

post params应该是这样的

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

但你的帖子参数很可能是

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%>

更新

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

在照片模型中添加这些,

accepts_nested_attributes_for :attachment
attr_accessible ..., :attachment_attributes

答案 1 :(得分:0)

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