Terence Devine
Terence Devine

Reputation: 125

Rails ActiveAdmin display image in has_many relationship

I have created a Production which has_many Galleries.

class Production < ApplicationRecord
  has_many :galleries
  accepts_nested_attributes_for :galleries, :allow_destroy => true
  ...

A Gallery has_one_attached Photo

class Gallery < ApplicationRecord
    has_one_attached :photo
end

In my ActiveAdmin form, I've added a has_many field and a conditional image to be shown.

...
f.has_many :galleries, allow_destroy: true do |g|
  g.input :photo, as: :file
  g.input :caption
  if g.object.photo.attached?
    image_tag(g.object.photo.variant(resize: '200x200^'))
  end
end
...

The image shows, the problem is the images shows separately from the related field. All uploaded images in the Gallery appear above the entire field - just above the Field Label. Is there any way to keep the related field and example image together in the markup? Any help would be greatly appreciated, Thanks!

Upvotes: 0

Views: 801

Answers (2)

Eli R.
Eli R.

Reputation: 188

I solved this using the :hint option, e.g.

g.input :photo, as: :file, hint: image_tag(g.object.photo.variant(resize: '200x200^'))

Upvotes: 1

Sjors Branderhorst
Sjors Branderhorst

Reputation: 2182

Try and surround the conditional with some arbre dsl:

li(:class => 'input') do
  label(:class => 'label') { "Preview" }
  div(:class => 'myCustomClass') do
    if g.object.photo.attached?
       # your code
    end
  end
end

The rails view helpers (like image_tag) do not always play well with arbre's output buffering.

Upvotes: 0

Related Questions