【问题标题】:why doesn't update_all work in rails with mongoid?为什么 update_all 不能在带有 mongoid 的 Rails 中工作?
【发布时间】:2012-11-09 05:12:40
【问题描述】:

我有一个 User 和 Notification 模型,User has_many Notification。通知由 kaminari 分页: 通知模型定义,

class Notification
  ...
  field read, type: Boolean, default: false
  belongs_to :user
  scope :recent, ->(source) { where(source: source).desc(:created_at) }
  ...
end

在通知控制器中,

@notifications = current_user.notifications.recent(@source).page(params[:page])

然后我想在渲染当前页面后将 read 属性更改为 true 但它不起作用:

@notifications.update_all(read: true)

read 属性在那里没有改变。而且我还有 1 件棘手的事情:

  1. 删除范围指令时(最近),update_all 可以工作,但它不仅会更新当前用户,还会更新所有其他用户。

我在我的瘦服务器中找到了一些日志,但没有发现错误:

MOPED: 127.0.0.1:27017 UPDATE       database=cse_development collection=notifi
cations selector={"$query"=>{"user_id"=>"509765c42061c79036000004", "source"=>"t
opic"}, "$orderby"=>{"created_at"=>-1}} update={"$set"=>{:read=>true}} flags=[:m
ulti] (0.9999ms)

我错过了什么吗?

提前致谢!

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    你可以试试这个

    @notifications.update_all(:read => true)
    

    【讨论】:

    • 我试过你的ide,但它对我不起作用。另外,我的 ruby​​ 版本是 1.9.3,所以我认为 hash 可以写成 read:true。我猜想方法“update_all”只能在标准对象上工作,但分页的“@notifications”是一个数组对象。不幸的是,它没有找到根本原因......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多