前提・実現したいこと
メルカリのクローンアプリ制作で、出品商品編集機能において、
変更なしの場合、
画像削除のみの場合、
画像以外の項目のみ変更した場合、
にDBを更新させたい。
商品(item)とその画像(image)はaccepts_nested_attributes_forでassociationを組んでいる。
発生している問題・エラーメッセージ
画像に何らかの変更を加えないと、どの項目も変更、削除、追加、更新できない。
該当のソースコード
routes.rb該当箇所
ruby
resources :items, only:[:show, :edit, :new, :create, :destroy, :update] do resources :comments, only: :create member do get 'confirm', to: 'items#confirm' post 'pay', to: 'items#pay' get 'done', to: 'items#done' post '/like/:item_id' => 'likes#like', as: 'like' delete '/like/:item_id' => 'likes#unlike', as: 'unlike' get 'get_category_children', defaults: { format: 'json' } get 'get_category_grandchildren', defaults: { format: 'json' } end collection do get 'get_category_children', defaults: { format: 'json' } get 'get_category_grandchildren', defaults: { format: 'json' } end end
item.rb
ruby
class Item < ApplicationRecord #省略 belongs_to :brand, optional: true belongs_to :user, optional: true has_many :comments, dependent: :destroy belongs_to :category, optional: true has_many :images, dependent: :destroy accepts_nested_attributes_for :images, allow_destroy: true has_many :likes, dependent: :destroy has_many :liking_users, through: :likes, source: :user belongs_to :category, optional: true validates :name, :description, :price, :area, :condition, :fee, :shipping_days, presence: true end
image.rb
ruby
class Image < ApplicationRecord belongs_to :item, optional: true validates_presence_of :item validates :content, presence: true mount_uploader :content, ImageUploader end
items_controller.rb
ruby
before_action :set_item, only: [:show, :edit, :update, :destroy, :pay, :confirm, :done] # 省略 def new @item = Item.new @brands = Brand.all @category_parent_array = ["指定なし"] Category.where(ancestry: nil).each do |parent| @category_parent_array << parent.name end @item.images.build end def create @item = Item.new(item_params) if @item.save && @item.images.count != 0 @image = @item.images.create redirect_to :root else flash.now[:alert] = '画像を1枚以上添付してください' render :new end end def edit @images = @item.images @brands = Brand.all @grandchild_category = @item.category @child_category = @grandchild_category.parent @parent_category = @child_category.parent @category_parent_array = ["指定なし"] Category.where(ancestry: nil).each do |parent| @category_parent_array << parent.name end @category_children_array = [] Category.where(ancestry: @child_category.ancestry).each do |child| @category_children_array << child end @category_grandchildren_array = [] Category.where(ancestry: @grandchild_category.ancestry).each do |grandchild| @category_grandchildren_array << grandchild end @item.images.build end def update if @item.update(item_params) @images = @item.images redirect_to item_path(@item) else flash.now[:alert] = '画像を1枚以上添付してください' redirect_to edit_item_path(@item) end end def destroy if @item.destroy redirect_to root_path else render :show end end def get_category_children @category_children = Category.find_by(name: "#{params[:parent_name]}", ancestry: nil).children end def get_category_grandchildren @category_grandchildren = Category.find("#{params[:child_id]}").children end private def item_params params.require(:item).permit( :name, :description, :price, :brand_id, :area, :condition, :fee, :category_id, :shipping_days, images_attributes: [:content, :id, :_destroy] ).merge(user_id: current_user.id) end def set_item @item = Item.find(params[:id]) end end
画像挿入部分
edit.html.haml
ruby
.main-items = form_with model: @item, local: true do |f| .wrapper.image-wrapper #image-box.image-wrapper__image-box = f.fields_for :images do |i| - if @item.persisted? = i.check_box :_destroy, data:{ index: i.index }, class: 'hidden-destroy' .image-wrapper__image-box__js.js-file_group{data:{index: "#{i.index}"}} = i.label :content, class: "image-wrapper__image-box__js__label" do .image-wrapper__image-box__js__label__image.img_field{id: "img_field--#{i.index}", data:{image: "#{i.index}"}, onClick: "$('#file').click()"} - if @item.images[i.index][:content].present? = image_tag asset_path(@images[i.index].content), width: "100%", height: "100%", class: "preview" - else = image_tag 'icon_camera.png', class: "image-wrapper__image-box__js__label__image__url", id: "default-img" = i.file_field :content, class: "image-wrapper__image-box__js__label__file js-file" .js-remove{data:{remove: "#{@images[i.index].id}"}} %span.js-remove__text 削除
edit.js
Javascript
$(function(){ // カテゴリー機能 # 省略 // 複数画像 $(window).on('load', function(e){ var fileIndex = [1,2,3,4,5,6,7,8,9,10]; var previewCount = $('.preview').length; lastIndex = $('.js-file_group:last').data('index'); fileIndex.splice(0, lastIndex); $('.hidden-destroy').hide(); $(document).on('change', '.js-file_group input', function(e) { $('.preview').parent().removeClass("img_field"); var id = $('.img_field').attr('id').replace(/[^0-9]/g, ''); var file = e.target.files[0]; var reader = new FileReader(); var newImgId = `#img_field--${id}`; var preview = $(newImgId); preview.attr({id: `img_field--${id}`}); reader.onload = (function(file) { return function(e) { preview.empty(); preview.append($('<img>').attr({ src: e.target.result, width: "100px", height: "100%", class: "preview", title: file.name })); }; })(file); preview.removeClass('img_field'); reader.readAsDataURL(file); }); const buildFileField = function(index){ var html = `<div class="image-wrapper__image-box__js js-file_group" data-index="${index}"> <label class="image-wrapper__image-box__js__label" for="item_images_attributes_${index}_content"> <div class="image-wrapper__image-box__js__label__image img_field" data-image="${index}" id="img_field--${index}" onclick="$('#file').click()"> <img class="image-wrapper__image-box__js__label__image__url" id="default-img" src="/assets/icon_camera-24c5a3dec3f777b383180b053077a49d0416a4137a1c541d7dd3f5ce93194dee.png"> </div> <input class="image-wrapper__image-box__js__label__file js-file" id="item_images_attributes_${index}_content" type="file" name="item[images_attributes][${index}][content]"> </label> <div class="js-remove" data-remove="${index}"> <span class="js-remove__text"> 削除 </span> </div> </div>`; return html; } $('#image-box').on('change', '.js-file', function(e){ if( previewCount < 9 || $('#default-img').length == 0) { $('#image-box').append(buildFileField(fileIndex[0])); fileIndex.shift(); fileIndex.push(fileIndex[fileIndex.length - 1] + 1) } }); $('#image-box').on('click', '.js-remove', function(){ const targetIndex = $(this).parent().data('index'); const hiddenCheck = $(`input[data-index="${targetIndex}"].hidden-destroy`); if (hiddenCheck){ hiddenCheck.prop('checked', true); } $(this).parent().remove(); if ($('.js-file').length == 0 || $('#default-img').length == 0){ $('#image-box').append(buildFileField(fileIndex[0])); }; }); }); });
試したこと
編集画面へ遷移⇨変更加えずそのまま送信ボタン⇨updateされずにedit画面に戻る。
編集画面へ遷移⇨画像以外の項目を変更して、送信ボタン⇨updateされずにedit画面に戻る。
編集画面へ遷移⇨画像数枚を削除して、送信ボタン⇨updateされずにedit画面に戻る。
編集画面へ遷移⇨画像を追加のみをし、送信ボタン⇨updateが成功し、showページへ。
編集画面へ遷移⇨画像の追加と削除をし、送信ボタン⇨updateが成功し、showページへ。
編集画面へ遷移⇨画像を追加と削除をし、その他の項目も変更し、送信ボタン⇨updateが成功し、showページへ。
結果わかったことは、
編集画面に遷移後、一度でも空の画像挿入ボックスもしくはそのボックスの削除ボタンをいじれば、画像も含め、その他の項目も変更、削除、追加可能になる。
おそらく、編集画面遷移後に、edit.jsファイルのプレビュー表示イベントか削除ボタンのイベントを一度でも発火させれば、正常に動く。
補足情報(FW/ツールのバージョンなど)
Ruby 2.5.1p57
Ruby on Rails (5.2.4.1)
jquery-rails (4.3.5)
ancestry (3.0.7)
carrierwave (2.1.0)
まだ回答がついていません
会員登録して回答してみよう