ruby-on-rails – 如何通过Paperclip rails上传图像,word文档和/或PDF文件4

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何通过Paperclip rails上传图像,word文档和/或PDF文件4前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想让用户将Word文档和PDF文件上传到我的rails应用程序.我的应用程序类似于Pinterest应用程序,用户可以在其附加图片的同时创建引脚,然后再进行说明(使用“纸张剪贴板将图像附加到引脚”).

这是我的引脚模型:

  1. class Pin < ActiveRecord::Base
  2. belongs_to :user
  3. has_attached_file :image,:styles => { :medium => "300x300>",:thumb => "100x100>" }
  4. validates_attachment :image,content_type: { content_type: ["image/jpg","image/jpeg","image/png","image/gif"] }
  5. validates :image,presence: true
  6.  
  7. end

我的引脚控制器:

  1. class PinsController < ApplicationController
  2. before_action :set_pin,only: [:show,:edit,:update,:destroy]
  3. before_action :correct_user,only: [:edit,:destroy]
  4. before_action :authenticate_user!,except: [:index,:show]
  5.  
  6. def index
  7. @pins = Pin.all.order("created_at DESC").paginate(:page => params[:page],:per_page => 15)
  8. end
  9.  
  10. def show
  11. end
  12.  
  13. def new
  14. @pin = current_user.pins.build
  15. end
  16.  
  17. def edit
  18. end
  19.  
  20. def create
  21. @pin = current_user.pins.build(pin_params)
  22. if @pin.save
  23. redirect_to @pin,notice: 'Pin was successfully created.'
  24. else
  25. render action: 'new'
  26. end
  27. end
  28.  
  29. def update
  30. if @pin.update(pin_params)
  31. redirect_to @pin,notice: 'Pin was successfully updated.'
  32. else
  33. render action: 'edit'
  34. end
  35. end
  36.  
  37. def destroy
  38. @pin.destroy
  39. redirect_to pins_url
  40. end
  41.  
  42. private
  43.  
  44. def set_pin
  45. @pin = Pin.find(params[:id])
  46. end
  47.  
  48. def correct_user
  49. @pin = current_user.pins.find_by(id: params[:id] )
  50. redirect_to pins_path,notice: "Not authorized to edit this Pin" if @pin.nil?
  51. end
  52.  
  53.  
  54. def pin_params
  55. params.require(:pin).permit(:description,:image)
  56. end
  57. end

我想知道我是否需要为我的Pin模型中的Word文档和PDF文件创建另一个has_attached_file方法,然后为用户创建一个用于上传文件的视图.

解决方法

这取决于…

如果要附加图像和文档,则需要为文档创建另一个纸张剪贴画属性.您的型号:

  1. has_attached_file :image,:thumb => "100x100>" }
  2. validates_attachment :image,"image/gif"] }
  3.  
  4. has_attached_file :document
  5. validates_attachment :document,:content_type => { :content_type => %w(application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document) }

如果要附加图像或文档,您可以执行以下操作:

  1. has_attached_file :document
  2. validates_attachment :document,:content_type => {:content_type => %w(image/jpeg image/jpg image/png application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document)}

如果您选择第一个选项,则您的视图中将需要两个文件输入,仅第二个选项.这不对还是错.这取决于你想做什么

猜你在找的Ruby相关文章