■解決したいこと
メルカリのようなフリマアプリの出品した商品の
出品した商品の編集画面にて非同期にて商品の複数画像のうち1つずつ削除できるような機能を実装しております。
編集画面に行き、保存されている画像の下に削除ボタンを設置し押したら該当の画像のみ画面から削除できるようにしたいです。
現在実装した内容では削除を押した段階で出品した商品全てが削除されてしまいます。
■自力で調べた内容
viewの削除ボタンをクリック→発火
コントローラーに定義したimage_destroyにjson通信。
コントローラーでjsで取得したimageIDのレコードを削除。
■仮説と検証作業の結果
通信は走っているがコントローラーで削除ができていない??
.new-conteiner
= render 'shared/new_header'
.new-main
.new-main__box
%h2 商品の情報を入力
= form_for @product do |f|
.image
%h4 出品画像
.image__images
- @image.each_with_index do |i, index|
- if i.image_url.present?
.image__images__box{"data-image-id": "#{i.id}"}
= image_tag(i.image_url.url, id: "product_image", class: "image-top imagemain#{index}", height: '120', width: '120')
.delete_btn 削除
$( document ).on('turbolinks:load', function() {
$(function(){
$(".delete_btn").on('click', function(){
var deleteConfirm = confirm('削除してよろしいでしょうか?');
if(deleteConfirm == true) { var clickEle = $(this) // var productEle = $(this).parent().parent().parent().parent(this); var imageID = clickEle.parent().attr('data-image-id') $.ajax({ url: 'image_destroy', type: 'POST', data: {'image_id': imageID, '_method': 'DELETE'} }) .done(function(){ clickEle.parent('img').remove(); }) .fail(function(){ alert('削除できませんでした') }); } else { (function(e){ e.preventDefault() }); }; });
});
});
```route.rb resources :products do member do get :buyer_show end collection do get 'get_category_children', defaults: { format: 'json' } get 'get_category_grandchildren', defaults: { format: 'json' } end member do get 'get_category_children', defaults: { format: 'json' } get 'get_category_grandchildren', defaults: { format: 'json' } end member do get 'image_destroy', defaults: { format: 'json' } end end ```controller.rb def edit @product = Product.find(params[:id]) @user = current_user @image = Image.where(product_id: @product) @category_parent_array = ["---"] Category.where(ancestry: nil).each do |parent| @category_parent_array << parent.name end end def destroy @products = current_user.products if @product.saler_id == current_user.id @product.destroy redirect_to show_exhibit_user_path(current_user) else render :show, notice: '削除できませんでした' end end def show end def update if @product.update(product_params) redirect_to product_path else render 'buyer_show' end end def buyer_show end def image_destroy image = Image.find(params[:image_id]) image.destroy render 'edit' end
あなたの回答
tips
プレビュー