【问题标题】:Updating a Rails model's attributes through mongoid using normal persistence methods使用普通的持久化方法通过 mongoid 更新 Rails 模型的属性
【发布时间】:2017-02-23 18:30:13
【问题描述】:

我一直在追查一个问题,但仍然无法弄清楚发生了什么。我无法通过正常的持久性方法(如update)编辑由我的 gem 制作的文档,甚至无法编辑属性并调用save

例如调用:

Scram::Policy.where(id: a.id).first.update!(priority: 12345)

根本不起作用(没有错误,但文档尚未更新)。但以下将正常工作:

Scram::Policy.collection.find( { "_id" => a.id } ).update_one( { "$set" => {"priority" => 12345}})

我不确定我做错了什么。在任何其他模型上调用更新和保存都可以正常工作。有问题的文档来自我的 gem:https://github.com/skreem/scram/blob/master/lib/scram/app/models/policy.rb

我也无法编辑它的嵌入文档(目标)。我尝试删除 store_in 宏,并在假应用中使用 inverse_ofclass_name 准确指定要使用的类来重新实现这些类:https://github.com/skreem/scram-implementation/blob/master/lib/scram/lib/scram/app/models/policy.rb

我尝试将整个 gem 重新实现为一个干净的假 rails 应用程序:https://github.com/skreem/scram-implementation

在 Rails 控制台中运行这些程序演示了更新是如何不起作用的: https://gist.github.com/skreem/c70f9ddcc269e78015dd31c92917fafa

这是关于嵌入式文档的 mongoid 问题,还是我的代码中遗漏了一些小的复杂性?

编辑: 如果您从我的 gem (scram) 的根目录运行 irb 然后运行以下命令,问题仍然存在:

require "scram.rb"
Mongoid.load!('./spec/config/mongoid.yml', :test)

Scram::Policy.first.update!(priority: 32) #=> doesn't update the document at all

Scram::Policy.where(id: "58af256f366a3536f0d54a61").update(priority: 322) #=> works just fine

奇怪的是,以下方法不起作用: Scram::Policy.where(id: "58af256f366a3536f0d54a61").first.update(priority: 322)

似乎first 没有检索到我想要的内容。进行相等比较表明第一个文档等于 where 查询返回的第一个文档。

【问题讨论】:

    标签: ruby-on-rails ruby mongodb mongoid persistence


    【解决方案1】:

    嗯。事实证明,您不能调用字段collection_name,否则 mongoid 将确保您遇到不好的事情。只需重命名该字段就解决了我所有的问题。这是导致冲突的 mongoid 中的代码:https://github.com/mongodb/mongoid/blob/master/lib/mongoid/persistence_context.rb#L82

    这是解决我问题的 gem 中的提交:https://github.com/skreem/scram/commit/25995e955c235b24ac86d389dca59996fc60d822

    编辑:

    如果您已处理此问题并且没有收到任何警告,请确保更新您的 Mongoid 版本!在 mongoid 问题跟踪器上创建问题后,PersistenceContext 被添加到禁止方法列表中。现在,尝试使用collection_namecollection 作为字段会导致mongoid 发出一些警告。

    修复提交:https://github.com/mongodb/mongoid/commit/6831518193321d2cb1642512432a19ec91f4b56d

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 1970-01-01
      • 2017-02-01
      • 2010-11-03
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 2015-01-17
      • 2012-04-12
      相关资源
      最近更新 更多