I have a model “Articles” that has_many “Assets” which is a polymorphic model that I attach images to using Paperclip.
When I am editing an Article, I want to be able to delete the old image, and add a new one in the same stroke. I am using fields_for which seemed versatile enough since the Rails API says I can use it for a specific instance of Assets. So here is the relevant portion of my form:
Form:
=f.fields_for :assets do |ff|
=ff.label "image"
=ff.file_field :image
-unless @article.assets.first.image_file_name.nil?
-@article.assets.each do |asset|
=f.fields_for :assets, asset do |fff|
=image_tag(asset.image.url(:normal))
=fff.label "delete image"
=fff.check_box :_destroy
The first fields_for is for adding images to articles, the second section is to delete assets that already exist. This form can add assets, delete assets, but it can’t do both at the same time.
That is the issue.
I suspect that the check_box is not directed enough or something.
Asset Model:
class Asset < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
has_attached_file :image, :styles => { :normal => "100%",:small => "100 x100>",:medium => "200x200>", :thumb => "50x50>" },
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => "/:attachment/:id/:style/:filename"
Article controller /edit:
def edit
@article = Article.find(params[:id])
@assets = @article.assets
if @assets.empty?
@article.assets.build
end
end
I look forward to seeing your responses.
With my pitiful cries for help falling on deaf ears I was forced to set out on my own (probably for the best). I discovered the solution by fiddling with the logic of the form. Below is the set up that allows me to add a Paperclip attachment and delete one (or more) in one form submission:
form:
My set up is: an
articlehas_manyassetswhich is a polymorphic model that holds image attachments for me.Research:
http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for
creating a form for deleting uploads that belongs to products
-second link: provided the insight to use
objectmethod on the form helper supplied byfields_for, in my case it isasset_fields.object...which allowed me to mess with instances of@assetsHere is the articles controller methods of interest: