ActiveStorage. 英文书Learnrails5.2的案例

本例子目标:增加一个avatar image给每个用户。

准备:

需要安装Imagemagick software。它可以create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats 。

可以使用打包管理软件homebrew安装brew install imagemagick。

在Rails,需要使用gem 'mini_magick' 。通过这个gem来使用Imagemagic的功能。

⚠️,我使用80template的时候,没有用这个gem,也能正常使用。

开始:

安装ative_storage:  rails active_storage:install

提示从active_storage迁移:

class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
  def change
    create_table :active_storage_blobs do |t|
      t.string   :key,        null: false
      t.string   :filename,   null: false
      t.string   :content_type
      t.text     :metadata
      t.bigint   :byte_size,  null: false
      t.string   :checksum,   null: false
      t.datetime :created_at, null: false
      t.index [ :key ], unique: true
    end
    create_table :active_storage_attachments do |t|
      t.string     :name,     null: false
      t.references :record,   null: false, polymorphic: true, index: false
      t.references :blob,     null: false
      t.datetime :created_at, null: false
      t.index [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true
    end
  end
end

解释:

t.index [:key], unique:true使用了index()方法,其内部使用了@base.add_index()方法,这个方法会生成sql语句,和数据库交互:

CREATE UNIQUE INDEX active_storage_blobs_key_index ON active_storage_blobs(key)

index的名字是表名+列名+_index后缀,太长的话,可以使用便名:add_index(name:"")

解释:

t.references :blob使用了关联方法add_references()方法,选项null:false是不得为空。

还有:type, :foreign_key, :index等方法。

type默认是digint长整数。

foreign_key:true用于本列被设置为关联外键。

index:true调用add_index方法给这个列增加索引。


新增的两个数据表会储存所有信息。user表无需增加一个额外的列,只需在User model中建立一个关联使用ActiveStorage::Attached#Marcos#has_one_attached 宏方法。

这里has_one_attached :avatar

然后就可以使用avatar方法了

解释:

Macros是宏命令的简写 Macroinstruction。

除此之前还has_many_attached(), 这里ActiveStorage会自动映射recoreds和the attachments。其实这个方法内部使用了has_many关联了attachments,使用了has_many-through关联了bolbs。

在控制台建立一个user,然后:

> user.avatar.attach(io: File.open("/Users/chentianwei/Desktop/1.jpeg"), filename: "1.jpeg", content_type: "image/jpeg")

#attach()方法可以用参数params[:avatar]或者ActiveStorage::blob object

解释:

  1. 首先从Attachment中找到关联的user.
  2. 文件信息上传,并自动生成一个key
  3. 把文件插入到Blob数据表中。包括文件名,类型,大小,key等信息。
  4. 如果1中没有现存的记录,此时在Attachment中建立记录,关联上user以及blob。
  5. user的updated_at属性更新。

可以使用user.avator.attached?  检测是否成功,返回true.

在views/users/show.html.erb增加这个图像。

<% if @user.avatar.attached? %>
  <p>
    <%= image_tag(url_for(@user.avatar), size: "200")%>
  </p>
<% end %>

在控制器端修改create和update:例子:

  def update
    avatar = params[:user][:avatar]
    respond_to do |format|
      if @user.update(user_params)
        if avatar
          @user.avatar.attach(avatar)
        end

在_form.html.erb中增加图片的上传操作:

<div>

<%= form.label :avatar %>

<%= form.file_field :avatar %>

</div>


增加了一个功能测试:测试文件上传是否成功:

attach_file("Avatar",  "#{Rails.root}/spec/files/1.jpeg")

还要在spec_helper中设置删除测试数据库中的文件具体见:

https://www.cnblogs.com/chentianwei/p/9071330.html


以上是基础,Active Storage还也可resize图片尺寸,可以把图片保存在云端的。具体看指导,和ruby-china的帖子。

可能先需要云服务器的知识,以及部署产品环境。

ActiveStorage. 英文书Learnrails5.2的案例,看如何放到云上。的更多相关文章

  1. 沉淀,再出发:结合案例看python

    沉淀,再出发:结合案例看python 一.前言 关于python,如果不经过大型程序开发的洗礼,我们很难说自己已经懂得了python了,因此,我们需要通过稍微结构化的编程来学习python. 二.一个 ...

  2. nigin配置安全:三个案例看Nginx配置安全(转)

    转:https://www.leavesongs.com/PENETRATION/nginx-insecure-configuration.html 三个案例看Nginx配置安全 PHITHON  之 ...

  3. 阿里云96页报告详解《云上转型》(10个案例、10大趋势/完整版PPT)

    阿里云96页报告详解<云上转型>(10个案例.10大趋势/完整版PPT) 2017-12-29 14:20阿里云/云计算/技术 ﹃产业前沿超级干货﹄ ﹃数据观○重磅速递﹄ 阿里云研究中心云 ...

  4. Java 8新的时间日期库,这二十个案例看完你还学不会算我的!!!

    Java对日期,日历及时间的处理一直以来都饱受诟病,尤其是它决定将java.util.Date定义为可修改的以及将SimpleDateFormat实现成非线程安全的.看来Java已经意识到需要为时间及 ...

  5. Mybatis案例超详解(上)

    Mybatis案例超详解(上) 前言: 本来是想像之前一样继续跟新Mybatis,但由于种种原因,迟迟没有更新,快开学了,学了一个暑假,博客也更新了不少,我觉得我得缓缓,先整合一些案例练练,等我再成熟 ...

  6. 从Windows角度看Mac OS X上的软件开发

    如果原来从事Windows软件开发,想跨足或转换至Mac OS X环境,需要知道那些东西?有什么知识技能可以快速运用在Mac OS X环境上的?这两个问题应该是Windows开发者进入Mac OS X ...

  7. Oracle案例02——ORA-12034: "SCOTT"."USER_TABLE" 上的实体化视图日志比上次刷新后的内容新

    最近同事在交接工作时,发现有几个schedule job没有执行成功,我这边给看了下,其中一个是由于数据库迁移,调用dblink的host主机IP在tnsnames中没有变更导致,还有一个是无法视图的 ...

  8. 许式伟看 Facebook 发币(上): 区块链, 比特币与 Libra 币

    你好,我是七牛云许式伟. Facebook(脸书)于6月18日发布了其加密数字货币项目白皮书.该数字货币被命名为 Libra(天秤座),象征着平衡与公正.此前,BBC 报道说这个数字货币叫 Globa ...

  9. 《一张图看懂华为云BigData Pro鲲鹏大数据解决方案》

    8月27日,华为云重磅发布了业界首个鲲鹏大数据解决方案--BigData Pro.该方案采用基于公有云的存储与计算分离架构,以可无限弹性扩容的鲲鹏算力作为计算资源,以支持原生多协议的OBS对象存储服务 ...

随机推荐

  1. Flum入门必备知识

    1.flume概念 flume是分布式的,可靠的,高可用的,用于对不同来源的大量的日志数据进行有效收集.聚集和移动,并以集中式的数据存储的系统. flume目前是apache的一个顶级项目. flum ...

  2. Convolution and polynomial multiplication

    https://www.mathworks.com/help/matlab/ref/conv.html?s_tid=gn_loc_drop conv Convolution and polynomia ...

  3. ubuntu ---QQ install/desktop/ibus reinstall

    http://www.linuxidc.com/Linux/2016-09/134923.htm ( Ubuntu 16.04安装QQ国际版图文详细教程) [ sudo apt-get install ...

  4. HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm

    HyperLogLog参考下面这篇blog, http://blog.codinglabs.org/articles/algorithms-for-cardinality-estimation-par ...

  5. Day03 javascript详解

    day03 js 详解 JavaScript的基础 JavaScript的变量 JavaScript的数据类型 JavaScript的语句 JavaScript的数组 JavaScript的函数 Ja ...

  6. 【抓包】火狐浏览器F12

    页面请求服务器的get.post两种请求,还有其他种,但是其他中基本不用,所以只记住get和post两种请求方法即可. 1.get(当前页面向服务器传值--即请求服务器)---弊端--传值长度有限 F ...

  7. 当IDENTITY_INSERT设置为OFF时不能向表插入显示值。(源:MSSQLServer,错误码:544)

    错误提示"事务和快照同步时提示:当IDENTITY_INSERT设置为OFF时不能向表插入显示值.(源:MSSQLServer,错误码:544)" 原因:在SQL2008同步时到S ...

  8. [Axiom3D]第一个Axiom3D程序

    Axiom3D程序的基本渲染流程 #region Namespace Declarations using System; using System.Linq; using Axiom.Core; u ...

  9. access 两表更新

    access 两表更新 update zz a inner join dz b  on  b.身份证号=a.身份证号 set a.电子学籍=b.学籍

  10. [LeetCode]160.Intersection of Two Linked Lists(2个链表的公共节点)

    Intersection of Two Linked Lists Write a program to find the node at which the intersection of two s ...