ruby使用carrierwave上传附件

使用carrierwave插件保存附件:
创建attachments多态表来实现附件的存储关联。
gem 'carrierwave'


[b]migration[/b]

class CreateAttachments < ActiveRecord::Migration[5.0]
def change
create_table :attachments do |t|
t.string :attachment_entity_type, limit: 64
t.integer :attachment_entity_id
t.string :path, comment: '文件类容'
t.string :name, comment: '文件名'
t.string :content_type, comment: '文件类型'
t.integer :file_size, comment: '文件大小'
t.integer :created_by, comment: '上传人'
t.timestamps
end
end
end

create_table "blogs", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "title"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "cover_img", comment: "封面"
t.integer "category_id", comment: "类型"
t.integer "view_count", comment: "文章访问次数"
t.integer "seq", default: 10, comment: "顺序"
end


[b]model[/b]

class Attachment < ApplicationRecord
#定义多态
belongs_to :attachment_entity, polymorphic: true, optional: true
#继承CarrierWave方法
mount_uploader :path, AttachmentUploader
before_save :set_fields

def set_fields
self.content_type = path.content_type
self.file_size = path.size
self.name = path.get_original_filename
end

def delete_company_attachment_it
self.destroy
true
end

def attachment_path
path.url
end

end


class Blog < ApplicationRecord
# 关联多态
has_many :attachments, as: :attachment_entity
belongs_to :category, optional: true
has_many :comments

def user_name
"@#{self.title}"
end

def self.view_count_top
order(view_count: :desc).limit(5)
end

def cover_img_path
self.cover_img ? Attachment.find(self.cover_img.to_i).path.url : "/assets/f10.jpg"
end

end



[b]AttachmentUploader[/b]

class AttachmentUploader < CarrierWave::Uploader::Base
def store_dir
"uploads/#{model.attachment_entity_type.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end


[b]controller[/b]

def create
@blog = Blog.new(blog_params)
attachment = Attachment.create(attachment_entity_type: "Blog",attachment_entity_id: @blog.id , path: params[:draft_img], created_by: 1 )
@blog.cover_img = attachment.id
@blog.save
end


[b]view[/b]

<%= form_for @blog, url: url, method: meth, :html => { :multipart => true } do |f| %>

<%= file_field_tag "draft_img", id: 'draft_img' %>
<%= f.text_field :title, class: 'form-control input-sm', style: 'width: 280px;' %>
<%= text_area_tag 'blog[content]', @blog.content %>

<%= f.submit :class=>"ui primary button"%>
<% end %>

你可能感兴趣的:(RUBY)