Question

I want to be able to delete images within my edit form using formtastic in Active_admin. There are many posts about this but I can't seem to get it to fit with my setup for some reason.

I have a Post model and a NewsImages model which holds images for each post:

class Post < ActiveRecord::Base

  has_many :news_images, dependent: :destroy
  accepts_nested_attributes_for :news_images, allow_destroy: true

end


class NewsImage < ActiveRecord::Base
  belongs_to :post
  has_attached_file :photo

end

So from what I have read a flag can be added to my NewsImage model, and have a before save method that will remove that image. I envisage it to look like this but it won't delete the image when clicking the checkbox.

#/admin/post.rb
  f.has_many :news_images do |p|
    if p.object.new_record?
      p.input :photo, as: :file
    else
    p.input :photo, as: :file, :hint => p.template.image_tag(p.object.photo.url(:thumb))
    p.input :remove_image, as: :boolean, required: :false, label: 'Remove image'

    end
  end 

Something I have noticed within the console at this stage is when clicking in and out of the checkbox it's value does not change to checked or unchecked; is it supposed to?

NewsImage model now looking like

class NewsImage < ActiveRecord::Base
  before_save :remove_photo
  belongs_to :post

  private

  def remove_photo
    self.photo.destroy if self.remove_image == '1'
  end

end

Is there anything here that would cause this not to work, or does someone have a solution for this kind of setup?

Était-ce utile?

La solution

Hopefully this will help someone in the same position. You dont need to build a custom method to delete images here, you simply use this in your form

 p.input :_destroy, as: :boolean, required: :false, label: 'Remove image'

and in your controller (permit_params) pass

:_destroy

within your nested attributes , eg

 permit_params :title, :content, :news_category_id, :author,
            news_images_attributes: [:id, :photo, :post_id, :_destroy]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top