我希望用户能够上传Word文档和PDF文件到我的Rails应用程序中。我的应用程序类似于Pinterest应用程序,用户可以创建“Pin”,并在其上附加图片和描述(使用Paperclip将图像附加到“Pin”)。以下是我的“Pin”模型:
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控制器:
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
我在想是否只需在我的 Pin 模型中为 Word文档 和 PDF 文件创建另一个 has_attached_file
方法,然后创建一个视图供用户上传文件。
:document
创建了一个新的输入,如下所示:<div class="form-group"> <%= f.label :document %><br> <%= f.file_field :document, class: "form-control" %> </div>
。 我尝试了它,并且它给了我一个错误undefined method document_content_type'
。 我的Pins控制器出了点问题: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
。 - Cyzanfarrails generate paperclip pin document
来创建迁移吗?这个生成器将在你的 Pin 模型上创建 document_file_name、document_file_size、document_content_type 和 document_updated_at 属性。 - Leantraxxxrails generate migration add_file_to_pin
然后rake db:migrate
。现在可以正常工作了。我必须考虑 MVC! - Cyzanfar<%= image_tag @pin.image.url(:medium) % >
吗?还是比这更复杂?如果是这样,我就必须深入研究并尝试自己解决问题。 - Cyzanfar