使用Paperclip将文档(DOC / DOCX)上载到Rails

时间:2015-04-30 09:48:42

标签: ruby-on-rails paperclip

我需要允许我的用户将Word文档(.doc文件)上传到我的应用程序。图片和PDF工作正常,但当我尝试上传文档时,我得到了:

undefined method `documents_path'

这是我的Document.rb文件中的代码。

      validates :title, presence: true
      validates :file,
        attachment_content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif", "application/pdf", 'application/msword','applicationvnd.ms-word','applicaiton/vnd.openxmlformats-officedocument.wordprocessingm1.document', 'text/plain']},
        attachment_size: { less_than: 5.megabytes }

      has_attached_file :file, styles: {
        thumb: '100x100>',
        square: '200x200#',
        medium: '350x350>',
        pdf_preview: '600x600>'}, processors: [:thumbnail]

以下是我的观点:

  <%= simple_form_for(@document, multipart: true) do |f| %>
    <%= f.input :title, :label => "Name of Document" %>
    <%= f.input :hotel_id %>
    <%= f.file_field :file, :label => "Upload Document" %>
    <%= f.submit 'Submit', :class => "btn btn-primary" %>
  <% end %>

我的路线:

resources :hotels do
    resources :advertisers
    resources :documents
end

2 个答案:

答案 0 :(得分:0)

因为您传递了@document,这是一个Document,所以rails会查找documents_path的路由,因为您已经将它嵌套在酒店内,所以该路由不存在。您还需要指定酒店:

<%= simple_form_for([@hotel, @document], multipart: true) do |f| %>
  ...

记得定义@hotel

答案 1 :(得分:0)

可能有点晚了,但在遇到同样的问题后,我找到了一个对我有用的解决方案。只需将以下内容放入名为(或创建)config/initializers/mime_types.rb

的文档中
Mime::Type.register "application/vnd.openxmlformats-officedocument.wordprocessingml.document", :docx

并且 docx 上传应该与引用的 content_type 一起使用。

现在,如果有人有兴趣像我一样只上传 pdfdocdocx,只需将以下内容放入您的模型中 >

validates_attachment_content_type :your_column_name, :content_type => ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
相关问题