1

我正在尝试使用 Carrierwave 上传多个文件。我尝试添加多文件功能,如 Carrierwave 的 github 页面所示,但老实说,这是有史以来最糟糕的事情。我找到了一个很好的来源,可以按照这些步骤上传多个文件。

1)rails new multiple_image_upload_carrierwave

2)

rails g scaffold post_attachment post_id:integer type_id:integer avatar:string

rake db:migrate

3)在post.rb中

class Post < ActiveRecord::Base
   has_many :post_attachments
   accepts_nested_attributes_for :post_attachments
end

4) 在 post_attachments.rb 中

class PostAttachment < ActiveRecord::Base
   mount_uploader :avatar, AvatarUploader
   belongs_to :post
end

5) 在 post_controller.rb 中

def show
   @post_attachments = @post.post_attachments.all
end

def new
   @post = Post.new
   @post_attachment = @post.post_attachments.build
end

def create


     @post = Post.new(post_params)

       respond_to do |format|
         if @post.save
           params[:post_attachments]['avatar'].each do |a|
              @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
           end
           format.html { redirect_to @post, notice: 'Post was successfully created.' }
         else
           format.html { render action: 'new' }
         end
       end
     end

     def update
       respond_to do |format|
         if @post.update(post_params)
           params[:post_attachments]['avatar'].each do |a|
             @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
           end
         end
      end

      def destroy
        @post.destroy
        respond_to do |format|
          format.html { redirect_to @post }
          format.json { head :no_content }
        end
      end


     private
       def post_params
          params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar])
       end

我的问题是,在头像字段中安装并上传的每个文件(.pdf)在 .pdf 扩展名之前都有一个唯一的后缀标识符。例如 XCF.pdf 和 BJHA.pdf。我有一个类型表,其中一列称为“后缀”。之前,当我只有一个文件上传时,它会在 create 方法中检查文件名扩展名的第一部分(在 .pdf 之前)是否存在于后缀列下的类型表中,如果存在,它会将 type_id 分配给该帖子文件。如果它没有找到后缀,则会出现验证错误。但是现在我有多个文件上传,并且我有一个名为 post_attachments 表的额外表,我不确定我应该在哪里执行此步骤来填充每个正在上传的文件的 type_id,因为每个文件都有它自己的 type_id。

我在想也许在 post_controler.rb 中的 if @post.save 之后的 create 函数中

    if @post.save
      params[:post_attachments]['avatar'].each do |a|
        @type = Type.where("sufix LIKE a.tr(.pdf,"")")
      if @type.exits?
        @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id, :type_id => @type.id)
      end
4

0 回答 0