More than 3 years have passed since last update.

posted at

Rails Console から ActiveStorage にファイルをアタッチする方法

ActiveStorage で色々試したみたかったので、 Console でアタッチできる方法を調べたときのメモ

Post モデルに、 has_one_attached :image してる想定

attach に して渡す

$ bin/rail c
irb(main):001:0> post = Post.first
irb(main):002:0> post.image.attach(io:"#{Rails.root}/tmp/test2.jpg"), filename: "test2.jpg", content_type: 'image/jpg')
irb(main):003:0> post.image.blob
  Post Load (0.6ms)  SELECT  `posts`.* FROM `posts` ORDER BY `posts`.`id` DESC LIMIT 1
  ActiveStorage::Attachment Load (0.4ms)  SELECT  `active_storage_attachments`.* FROM `active_storage_attachments` WHERE `active_storage_attachments`.`record_id` = 3 AND `active_storage_attachments`.`record_type` = 'Post' AND `active_storage_attachments`.`name` = 'image' LIMIT 1
  ActiveStorage::Blob Load (0.4ms)  SELECT  `active_storage_blobs`.* FROM `active_storage_blobs` WHERE `active_storage_blobs`.`id` = 9 LIMIT 1
=> #<ActiveStorage::Blob id: 9, key: "amiLLH8AjxFhUSuvfvo3mFZa", filename: "text.jpg", content_type: "image/jpeg", metadata: {"identified"=>true, "width"=>1478, "height"=>1108, "analyzed"=>true}, byte_size: 728402, checksum: "FWotSOkUUkLMxmmearPQNQ==", created_at: "2019-04-18 07:11:40">

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up