Ask A Question


You’re not receiving notifications from this thread.

Select cover image from ActionText attachments

gorka asked in Rails

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 %>
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 81,149+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.