[Ruby] Rails6: Take out the image in Action Text

less than 1 minute read

前提

Rails:6.0.3.2 使うモデル名:Article リッチテキストのフィールド名:body

実際に画像を取り出す


@article = Article.first
@images = @article.body.embeds
ActionText::RichText Load (0.5ms)  SELECT `action_text_rich_texts`.* FROM `action_text_rich_texts` WHERE `action_text_rich_texts`.`record_id` = 1 AND `action_text_rich_texts`.`record_type` = 'Article' AND `action_text_rich_texts`.`name` = 'body' LIMIT 1

一つめの画像を取り出したいとき

@images.first.blob
ActiveStorage::Attachment Load (0.6ms)  SELECT `active_storage_attachments`.* FROM `active_storage_attachments` WHERE `active_storage_attachments`.`record_id` = 1 AND `active_storage_attachments`.`record_type` = 'ActionText::RichText' AND `active_storage_attachments`.`name` = 'embeds' ORDER BY `active_storage_attachments`.`id` ASC LIMIT 1
ActiveStorage::Blob Load (0.4ms)  SELECT `active_storage_blobs`.* FROM `active_storage_blobs` WHERE `active_storage_blobs`.`id` = 1 LIMIT 1
=> #<ActiveStorage::Blob id: 1, key: "rt0856j7x8btuev1ncbuurjgjyq4", filename: "1_xxo_q17kxed6bI9O_E8ZcA.png", content_type: "image/png", metadata: {"identified"=>true, "width"=>512, "height"=>512, "analyzed"=>true}, byte_size: 14483, checksum: "5qx1/QPniLbLvo07uUFsOw==", created_at: "2020-07-16 11:40:19">

存在確認

@images.present?
ActiveStorage::Attachment Exists? (0.6ms)  SELECT 1 AS one FROM `active_storage_attachments` WHERE `active_storage_attachments`.`record_id` = 1 AND `active_storage_attachments`.`record_type` = 'ActionText::RichText' AND `active_storage_attachments`.`name` = 'embeds' LIMIT 1
=> true