除非刷新浏览器,否则对象不会更新-原因是Turbolink?

时间:2019-02-06 14:12:39

标签: ruby-on-rails

我有一个产品型号,我的问题出在编辑/更新操作上

当我要编辑字段时,无法提交表单,但是在终端中没有显示错误。

如果我刷新浏览器,请编辑任何字段并提交,然后它就会起作用...

为什么必须刷新浏览器才能编辑对象?我做错了什么?

edit.html.erb

<%= simple_form_for(@product, url: admin_product_path(@product)) do |f| %>      
  <%= f.input :price, label: false, required: true %>
  <%= f.input :description, placeholder: "Description", label: false, required: true %>
  <%= f.input :brand, placeholder: "Marque", label: false, required: true %>
  <%= f.input :title, placeholder: "Titre", label: false, required: true %>
 <%= f.file_field :attachments, multiple: true, class: "file-upload-input", id: "files", required: true %>
  <%= f.submit %>
<% end %>

  # I am adding or deleting images with another controller so that's why I have this modal here. 
 <button type="button" class="btn btn-main add-pic-modal" data-toggle="modal" data-target="#addpicmodal">Ajouter des images</button>

_modal_add_pic.html.erb

  <%= simple_form_for @product, url: admin_product_attachments_path(@product), method: :post do |f| %>
    <%= f.file_field :attachments, multiple: true, class: "file-upload-input", id: "files" %>
    <h3>Glisser Déposer images</h3>
    <h3> Vous pouvez ajouter encore <%= 4 - @product.attachments.size %> image </H3>
    <div id="result"></div> 
    <%= f.button :submit, "Envoyer", class: "btn btn-main",  id:"modal-submit" %>
    <%= link_to  "annuler", "#", id: "refreshModal", class: "btn btn-secondary" %>
  <% end %>

products_controller.rb

class Admin::ProductsController < Admin::ApplicationController
  protect_from_forgery
  before_action :authenticate_user!, only: [:new, :create, :destroy , :update, :edit]
  before_action :set_product, only: [:show, :destroy, :update, :edit]

  def edit
  end

  def update
    if @product.update_attributes!(params_product)
      respond_to do |format|
        format.html {redirect_to admin_product_path(@product), notice: "L'article a bien été modifié"}
        format.js
      end
    else
      render :edit, alert: "Woooops"
    end
  end

  private

  def set_product
    @product = Product.find(params[:id])
  end

  def params_product
    params.require(:product).permit(:title, :ref, :brand, :description, :price, :category_id, :color, { attachments:[]}, sizes_attributes: [:id, :size_name, :quantity, :_destroy])
  end
end

# just in case my product.rb
class Product < ApplicationRecord
  mount_uploaders :attachments, AttachmentUploader

  belongs_to :user, optional: true
  belongs_to :category, optional: true

  has_many :favorites, dependent: :destroy
  has_many :favoriting_users, through: :favorites, source: :user
  has_many :sizes, inverse_of: :product, dependent: :destroy
  has_many :order_items, dependent: :destroy

  accepts_nested_attributes_for :sizes, reject_if: :all_blank, allow_destroy: true

  validates :title,       presence: true
  validates :price,       presence: true
  validates :description, presence: true
  validates :color,       presence: true
  validates :brand,       presence: true
  validates :category_id, presence: true
  validates :ref,         presence: true

  validate  :attachment_size
  validate  :at_least_one_size, on: :create    

  private

  def attachment_size
    if self.attachments.count < 1
      errors.add(:base, :inferior_quota)
    elsif self.attachments.count > 4
      errors.add(:base, :exceeded_quota)
    end
  end   

  def at_least_one_size
    if self.sizes.empty?
      errors.add(:base, :require_size)
    end
  end
end

编辑

当我删除turbolink时,它又可以正常工作了,所以我尝试在编辑表单中添加它,但这无济于事...

 <% content_for(:body_attributes) do %>
    data-turbolinks="false"
  <% end %>

application.js

//= require jquery3
//= require popper
//= require bootstrap-sprockets
//= require jquery
//= require rails-ujs
//= require turbolinks
//= require cocoon
//= require bootstrap-datepicker
//= require highcharts
//= require chartkick
//= require_tree .

window.setTimeout(function() {
   $(".alert").fadeTo(1000, 0).slideUp(2000, function() {
       $(this).hide();
   });
}, 3000);

product_images.js

function handleFileSelect() {
  //Check File API support
  if (window.File && window.FileList && window.FileReader) {

      var files = event.target.files; //FileList object
      var output = document.getElementById("result");

      for (var i = 0; i < files.length; i++) {
          var file = files[i];
          //Only pics
          if (!file.type.match('image')) continue;

          var picReader = new FileReader();
          picReader.addEventListener("load", function (event) {
            var picFile = event.target;
            var li = document.createElement("li");
            li.className ='list'

            li.innerHTML = "<img class='thumbnail small_image' src='" + picFile.result + "'" + "title='" + picFile.name + "'/></br>";

            output.insertBefore(li, null);
          });
          //Read the image
          picReader.readAsDataURL(file);
      }
  } else {
      console.log("Your browser does not support File API");
  }
}

var element = document.getElementById('files')

if(element != null){
  document.getElementById('files').addEventListener('change', handleFileSelect, false);  
}

///////////////////////////////////////////////////////////////////////////////////////////////

// Modal ajout d'image
var refresh = document.getElementById('refreshModal');
 refresh.addEventListener('click', function(){
  location.reload();
 })


function checkImageCounter(event){

  var tinyImagesCounter = Array.from(document.getElementsByClassName('tiny_image')).length
  var smallImagesCounter = Array.from(document.getElementsByClassName('small_image')).length

  var resultCounter = tinyImagesCounter + smallImagesCounter;

  var divTextUpload = document.getElementsByClassName('image-upload-wrap')[0];
  var submitNewImage = document.getElementById("modal-submit");


  if(resultCounter >= 5){
    divTextUpload.style.color= "red";
    divTextUpload.innerHTML = "<h3>OULA! Il ne peut y avoir que quatre images en tout!</h3>"
    submitNewImage.setAttribute("disabled", true)
    event.preventDefault();
    }
  else if (smallImagesCounter === 0 ){
    divTextUpload.style.color= "red";
    divTextUpload.innerHTML = "<h3>OULA! Séléctionnez au moins une image</h3>"
    submitNewImage.setAttribute("disabled", true)
    event.preventDefault();
  }
}

var submitNewImage = document.getElementById("modal-submit");

submitNewImage.addEventListener('click', checkImageCounter, false)

1 个答案:

答案 0 :(得分:0)

在此页面上重定向我的data: { turbolinks: false }中添加link_to可以解决我的问题