Liangchao's blog
一个技术商人的笔记
github
|
email
Toggle navigation
Liangchao's blog
主页
归档
关于我
津ICP备17001227号
Rails-Gem-carrierwave 上传文件
2017-10-23 19:58:33
78
0
0
liangchaob@163.com
# 步骤 ## 安装 ``` gem 'carrierwave' ``` cli中 ``` bundle install ``` 然后可以新建一个uploader ``` rails g uploader attachment ``` 然后需要设置一下app/uploaders/attachment_uploader.rb,一般默认即可 ``` storage :file def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end ``` 结果大致是这样的 ``` # Include RMagick or MiniMagick support: # include CarrierWave::RMagick # include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end ``` ## 使用 Model中 需要将其设置如下 ,当然需要先添加一个对应的column ``` rails g migration add_attachment_to_product ``` 修改db/migrate/add_attachment_to_product.rb ``` class AddImgToProduct < ActiveRecord::Migration[5.0] def change add_column :products, :attachment, :string end end ``` 修改model挂载 ``` class Resume < ApplicationRecord # 添加上传设置 mount_uploader :attachment, AttachmentUploader end ``` Controller中 注意打开上传的新项目 ``` def product_params params.require(:product).permit(:title, :description, :image,:quantity, :price, :feet,:attachment) end ``` View中 使用 ``` <%= f.input :attachment ,label: '附件'%> ``` 链接 ``` <% if resume.attachment.present? %> <a href="<%= resume.attachment_url %>" target="_blank" class="btn btn-primary btn-xs">预览</a> <% else %> <p>无附件</p> <% end %> ``` 或者也可以用`image_tag` ``` <%= image_tag(current_user.avatar_url, :height => '120', :width => '90') %> ``` 文件名 ``` .attachment_identifier ```
上一篇:
Rails-Config-更改数据库create_at 的UTC时间为北京时间
下一篇:
JS-Tag-标签编辑器tag-it用法
0
赞
78 人读过
新浪微博
微信
腾讯微博
QQ空间
人人网
提交评论
立即登录
, 发表评论.
没有帐号?
立即注册
0
条评论
More...
文档导航
没有帐号? 立即注册