###環境
Ruby(2.3.3)
Ruby on Rails(5.0.1)
gem
carrierwave(アップローダー)
cocoon(ネストフォーム)
保存先
Cloudinary
###保存されている画像ファイルを更新時に取得したい
こちらを参照してRailsの画像アップロードフォームにプレビューを表示させました。
新規登録時はこのままで問題ないのですが、現状edit(更新)画面では空欄のままとなっており事前に保存されている画像を枠内に表示させたいと考えております。
以下のJSファイルを編集が必要かと思いますが、どの部分を変更すれば良いのか教えて頂けませんでしょうか。。
なお、image(画像)モデルはshop(店舗)モデルにネストされています。
JavaScript
$(document).on('change', ':file', function() { var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1, label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); input.parent().parent().next(':text').val(label); var files = !!this.files ? this.files : []; if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support if (/^image/.test( files[0].type)){ // only image file var reader = new FileReader(); // instance of the FileReader reader.readAsDataURL(files[0]); // read the local file reader.onloadend = function(){ // set image data as background of div input.parent().parent().parent().prev('.imagePreview').css("background-image", "url("+this.result+")"); } } });
サーバーサイドはこのようになっております
ruby
class Shop < ApplicationRecord has_many :images, dependent: :destroy accepts_nested_attributes_for :images, allow_destroy: true
ruby
class Image < ApplicationRecord belongs_to :shop, optional: true mount_uploader :file, ImageUploader end
Ruby
def new @shop = Shop.new @shop.build_close_date 2.times { @shop.images.build } end def edit @shop.close_date = CloseDate.new if @shop.close_date.blank? end def create @shop = current_user.shops.build(shop_params) respond_to do |format| if @shop.save format.html { redirect_to @shop, notice: '店舗情報を登録しました' } format.json { render :show, status: :created, location: @shop } else format.html { render :new } format.json { render json: @shop.errors, status: :unprocessable_entity } end end end def update if @shop.update(shop_params) format.html { redirect_to @shop, notice: '店舗情報を更新しました' } format.json { render :show, status: :uploded, location: @shop } else format.html { render :edit } format.json { render json: @shop.errors, status: :unprocessable_entity } end end end
HTML
<%= simple_form_for(@shop, :authenticity_token => true, html: { multipart: true }) do |f| %> <div class="nested-field"> <%= f.simple_fields_for :images do |image| %> <%= render partial: 'image_fields', locals: {f: image} %> <% end %> <%= link_to_add_association "画像を追加", f, :images, :class => 'btn btn-primary' %> </div> <% end %>
HTML
<div class="nested-fields form_time_selects imgInput"> <div class="col-sm-2"> <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary"> 選択<%= f.file_field :file, :class => "uploadFile", :style => "display:none" %> <%= link_to_remove_association("削除", f, {}) %> </span> </label> <input type="text" class="form-control" readonly=""> </div> </div> <%#= link_to_remove_association("削除", f, {}) %> </div>
まだ回答がついていません
会員登録して回答してみよう