A
A
Anton Ipatov2019-01-24 17:28:31
MongoDB
Anton Ipatov, 2019-01-24 17:28:31

How to make MongoDB update the position field?

I want to update the position field of Attachinary::File
I'm using ruby ​​2.5.0, rails 5.2.2, mongoid, 'jquery-ui-rails' and modified Attachinary gem to load
application.js images

jQuery(function() {
  $(document).on('turbolinks:load', function(){
    $('.attachinary-input').attachinary()

    $("#images").sortable({
      update: function(e, ui) {
        Rails.ajax({
          url: $(this).data("url"),
          type: "PATCH",
          data: $(this).sortable('serialize'),
        });
      }
    });
  });
})

routes.rb
resources :projects do
    collection do
      patch :sort
    end
end

project.rb
class Project
  include Mongoid::Document

  has_attachments :images
end

show.html.erb
<div id="images" class="grid" data-url="<%= sort_projects_path %>">
  <% @project.images.order(position: :desc).each do |image| %>
    <div id="image_<%= image.id %>" class="box">
      <div class="box-image">
        <%= cl_image_tag(image.path, width: '250', height: '250', crop: 'thumb') %>
      </div>
    </div>
  <% end %>
</div>

projects_controller.rb
class ProjectsController < ApplicationController
  def sort
    params[:image].each_with_index do |id, index|
      Attachinary::File.where(id: id).update_all(position: index + 1)
    end
    head :ok
  end

When you try to drag an image, the following message appears. But position is not updated :
}} MONGODB | localhost:27017 | squarely_development.find | SUCCESSED | 0.001s Completed 200 OK in 6ms }} MONGODB | localhost:27017 | squarely_development.find | SUCCESSED | 0.001s Completed 200 OK in 6ms
end

If I use ActiveRecord and gem 'pg' everything works

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question