LoginSignup
2
3

More than 3 years have passed since last update.

【Rails】Action TextとActive Storageテーブルのデータ取得

Last updated at Posted at 2020-05-30

概要

ArticleモデルでActionTextを使おうと思った場合、次のようにすれば「action_text_rich_texts」テーブルのデータを取得できるが、一緒に作成される他二つのテーブルのデータを取得できず四苦八苦した。。。

class Article < ApplicationRecord
  has_rich_text :content
end
$ Article.first.content

結果

それぞれ次のコードで取り出せた。

$ ActiveStorage::Attachment
=> ActiveStorage::Attachment(
id:          integer, 
name:        string, 
record_type: string, 
record_id:   integer, 
blob_id:     integer, 
created_at:  datetime
)

$ ActiveStorage::Blob
=> ActiveStorage::Blob(
id:           integer, 
key:          string, 
filename:     string, 
content_type: string, 
metadata:     text, 
byte_size:    integer, 
checksum:     string, 
created_at:   datetime
)


$ ActionText::RichText
=> ActionText::RichText(
id:          integer, 
name:        string, 
body:        text, 
record_type: string, 
record_id:   integer, 
created_at:  datetime, 
updated_at:  datetime
)

やりたかったこと

ActionTextに関連づいた画像を一覧表示して、画像にArticleの詳細ページへのpathを指定したかった。
とりあえず実現はできたが以下のような回りくどいコードになった。
外部キーも設定されているようだし、もっとうまいこと呼びだせると思うけど分からず、、、、
わかる方、是非教えていただけないでしょうかm(_ _)m

app/controllers/pages_controller.rb
  def photo
    # 関連付けされているBlobのみ取得
    blob_ids = ActiveStorage::Attachment.pluck(:blob_id)
    @blob = ActiveStorage::Blob.where(id: blob_ids )
    # Blobに対応したログのidを取得
    attachment = ActiveStorage::Attachment.where(blob_id: @blob.ids)
    @link = attachment.pluck(:record_id)
  end
html.erb
<div>
  <% @blob.zip(@link).each do |img, link| %>
    <%= link_to article_path(link) do %>
      <%= image_tag img %>
    <% end %>
  <% end %>
</div>
2
3
0

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
  3. You can use dark theme
What you can do with signing up
2
3