首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何通过剪纸rails 4上传图像、word文档和/或PDF文件

如何通过剪纸rails 4上传图像、word文档和/或PDF文件
EN

Stack Overflow用户
提问于 2014-07-12 18:12:56
回答 1查看 18.7K关注 0票数 17

我希望用户能够将Word文档、PDF文件上传到rails应用程序。我的应用程序类似于Pinterest应用程序,用户可以创建Pins,用户可以在其中附加图片和描述(使用Paper剪贴画将图像附加到Pin)。

下面是我的Pins模型:

代码语言:javascript
复制
class Pin < ActiveRecord::Base
    belongs_to :user
    has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
    validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
    validates :image, presence: true

    end

我的Pins控制器:

代码语言:javascript
复制
class PinsController < ApplicationController
  before_action :set_pin, only: [:show, :edit, :update, :destroy]
  before_action :correct_user, only: [:edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
    @pins = Pin.all.order("created_at DESC").paginate(:page => params[:page], :per_page => 15)
  end

  def show
  end

  def new
    @pin = current_user.pins.build
  end

  def edit
  end

 def create
    @pin = current_user.pins.build(pin_params)
    if @pin.save
      redirect_to @pin, notice: 'Pin was successfully created.'
    else
      render action: 'new'
    end
  end

  def update
    if @pin.update(pin_params)
      redirect_to @pin, notice: 'Pin was successfully updated.'
    else
      render action: 'edit'
    end
  end

  def destroy
    @pin.destroy
    redirect_to pins_url
  end

  private

    def set_pin
      @pin = Pin.find(params[:id])
    end

    def correct_user
      @pin = current_user.pins.find_by(id: params[:id] )
      redirect_to pins_path, notice: "Not authorized to edit this Pin" if @pin.nil?
    end


    def pin_params
      params.require(:pin).permit(:description, :image)
    end
end

我想知道我是否只需要为我的has_attached_file Pin模型中的Word docsPDF文件创建另一个方法,然后为用户创建一个视图来上传该文件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-12 18:53:37

这取决于..。

如果要附加图像和文档,则需要为文档创建另一个回形针属性。在你的模型上:

代码语言:javascript
复制
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }

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

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

代码语言:javascript
复制
has_attached_file :document
validates_attachment :document, :content_type => {:content_type => %w(image/jpeg image/jpg image/png application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document)}

如果您选择第一个选项,您将需要在视图中输入两个文件,而第二个只需要一个。这件事不对也不对。这取决于你想做什么。

票数 37
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24715918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档