2

我正在尝试使用多态关联来减少文件管理在简单的 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'
4

2 回答 2

6

后参数应该是这样的

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
于 2013-04-13T17:51:35.023 回答
0
<%=form_for @photo do |photo_f|%>
 ....
 <%=photo_f.fields_for :attachment_attributes do |attachment_f|%>
  <%= attachment_f.file_field :file %>
 <%end%>
 ....
<%end%>
于 2015-04-06T12:36:07.147 回答