Mongoid不会更新排名字段

时间:2019-01-24 12:23:01

标签: ruby-on-rails ruby mongodb mongoid

我希望能够更新Attachinary :: File position字段

我使用ruby 2.5.0,rails 5.2.2,mongoid,'jquery-ui-rails'和自定义附件https://github.com/ipatovanton/attachinary/tree/position)来上传图片。

application.js

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
end

当我尝试拖动图像时,会收到下一条消息。但是位置没有更新:

  

在2019-01-23 18:19:46为127.0.0.1启动PATCH“ / projects / sort”   +0300由ProjectsController#sort作为 / 处理参数:{“ image” => [“ 5c4827691996da1fef832f5d”,“ 5c4827691996da1fef832f6e”,   “ 5c4827691996da1fef832f5e”,“ 5c4827691996da1fef832f5f”,   “ 5c4827691996da1fef832f60”,“ 5c4827691996da1fef832f61”,   “ 5c4827691996da1fef832f62”,“ 5c4827691996da1fef832f63”,   “ 5c4827691996da1fef832f64”,“ 5c4827691996da1fef832f65”,   “ 5c4827691996da1fef832f66”,“ 5c4827691996da1fef832f67”,   “ 5c4827691996da1fef832f68”,“ 5c4827691996da1fef832f69”,   “ 5c4827691996da1fef832f6a”,“ 5c4827691996da1fef832f6b”,   “ 5c4827691996da1fef832f6c”,“ 5c4827691996da1fef832f6d”,   “ 5c4827691996da1fef832f5c”]} MONGODB |本地主机:27017 |   squarely_development.find |已开始| {“查找” =>“用户”,   “ filter” => {“ _ id” => BSON :: ObjectId('5c472c2e1996da1d037f57fb')},   “ sort” => {“ _ id” => 1},“ limit” => 1,“ singleBatch” => true,   MONGODB |“ lsid” => {“ id” =>}}本地主机:27017 |   squarely_development.find |成功| 0.001s在6ms内完成200 OK

如果我使用ActiveRecord和gem'pg'一切正常

但是我需要这种解决方案才能与Mongodb一起使用

有人对此有任何想法或想法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

首先,您似乎正在尝试对项目的图像进行排序。

如果是这样,那么我建议将此路线移至成员而不是集合上。

这意味着您将必须添加sort_project_path(@project)。 如果您以与访问图像相同的方式来检索图像,则可以使我们的生活更轻松。

class ProjectsController < ApplicationController
  before_action :set_project # You may already have that

  def sort
    params[:image].each_with_index do |id, index|
      @project.images.where(id: id).update_all(position: index + 1)
    end
    head :ok
  end

  def set_project
    @project = Project.find(params[:id])
  end
end

我希望对您有用。