Reputation: 15374
Using Carrierwave as normal for my image upload, on this occasion a user can upload an image and assign a status of 'Before' or 'After' to an image.
I am having trouble removing an image, so for example in this part of the edit form
<%= f.fields_for :portfolio_images do |i| %>
<% if i.object.status == 'Before' %>
<div class="form-group">
<%= i.label 'Before' %><br>
<%= image_tag(i.object.image_url(:thumb)) %><br>
<label>
<%= i.check_box :remove_image %>
Remove Image
</label>
</div>
<% end %>
<% end %>
The image with the status Before will show but when clicking the check box to remove the image the image is still present. I have added remove_image to my permitted params so not sure what else to do here
def portfolio_params
params.require(:portfolio).permit(:id, :title, :description, portfolio_images_attributes:[:id, :portfolio_id, :image, :status, :image_cache, :remove_image])
end
Here are the params that are being passed
Parameters: {"utf8"=>"✓", "authenticity_token"=>"WDRAWPkQoIF2OkFk8gZpN5niUs3+PcpDRsJ/DvQ0JMk=", "portfolio"=>{"title"=>"Garden Lawn", "description"=>"Lorem Ipsum", "portfolio_images_attributes"=>{"0"=>{"remove_image"=>"1", "id"=>"1"}, "1"=>{"remove_image"=>"0", "id"=>"2"}}}, "commit"=>"Submit", "id"=>"6"}
Thanks
Upvotes: 2
Views: 1048
Reputation: 405
CarrierWave requires that you add something like the following to your portfolio_image_attributes:
:_destroy
Once you add that, you'll need to update your checkbox to reference that attribute. I'm not sure if you created ":remove_image" yourself, but I don't think it's necessary.
I added a checkbox (actually, in my app it's a hidden field) that looks like this:
<%= f.hidden_field :_destroy %> #(Where f references my portfolio_image, NOT my portfolio)
Then, upon clicking the X (which references my hidden_field) and submitting my form, the image is removed. Remember, if your image uploader is a has_many relation with the a parent model, you need to add allow_destroy: true to the accepts_nested_attributes. Otherwise it will not allow you to destroy the image from the parent form.
portfolio.rb:
has_many :portfolio_images, dependent: :destroy
accepts_nested_attributes_for :portfolio_images, allow_destroy: true
Upvotes: 4