2,550 Experience
25 Lessons Completed
0 Questions Solved


Posted in Select cover image from ActionText attachments

I wanted to add a “cover image” feature to a blog. I’m already using ActionText for the content.

I’m not sure if this is a good idea or if there are better ways to do it. I’m going to explain what I did and see if you have any comments about it.

I added a cover_attachment_id field to my Post model.

In the form I loop through all the content embeds and render a collection of radio buttons to select the cover image.

<% if post.content.embeds.any? %>
  <p>Select cover image:</p>
  <div class="post_cover_select">
    <%= collection_radio_buttons(:post, :cover_attachment_id, post.content.embeds.all, :id, :created_at) do |b|
      b.label(class: "post_cover_radio_button") {
        image_tag(b.object.variant(resize_to_fit: [150, 150])) + b.radio_button
    end %>
<% end %>

To render the cover image I created a helper:

def cover_image(attachment_id)
  full_url_for ActiveStorage::Attachment.find(attachment_id).variant(resize_to_limit: [600, 600])

I see in the example from the Ruby On Rails website they go easier with just has_one_attached :cover_image in the model but I wanted to avoid uploading twice the same image.

Any thoughts? Thanks!


Another option is to add a method in the model:

def cover
  if cover_attachment_id
    content.embeds.find_by(id: cover_attachment_id).variant(resize_to_limit: [600, 600])

And use it from the views:

<%= image_tag post.cover if post.cover %>

<%= full_url_for post.cover if post.cover %>