3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails JS】フォームで画像ファイルのプレビューをeditでも表示したい

Posted at

環境

Ruby(2.3.3)
Ruby on Rails(5.0.1)

gem
carrierwave(アップローダー)
cocoon(ネストフォーム)

保存先
Cloudinary

保存されている画像ファイルを更新時に取得したい

こちらを参照してRailsの画像アップロードフォームにプレビューを表示させました。

スクリーンショット 2017-03-07 7.54.54.png

新規登録時はこのままで問題ないのですが、現状edit(更新)画面では空欄のままとなっており事前に保存されている画像を枠内に表示させたいと考えております。

スクリーンショット 2017-03-07 7.56.19.png

以下のJSファイルを編集が必要かと思いますが、どの部分を変更すれば良いのか教えて頂けませんでしょうか。。
なお、image(画像)モデルはshop(店舗)モデルにネストされています。

shop.js
$(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+")");
        }
    }
});

サーバーサイドはこのようになっております

shop.rb
class Shop < ApplicationRecord
  has_many :images, dependent: :destroy
  accepts_nested_attributes_for :images, allow_destroy: true
image.rb
class Image < ApplicationRecord
  belongs_to :shop, optional: true
  mount_uploader :file, ImageUploader
end
shops_controller.rb
  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
_form.html.erb
<%= 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 %>
_image_fields.html.erb
<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>
</div>
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?