【问题标题】:Updating attributes on several indexes in array. Using mongoid in Rails 3更新数组中多个索引的属性。在 Rails 3 中使用 mongoid
【发布时间】:2011-10-17 07:08:19
【问题描述】:

在我的测试数据库中,我想触发一个“new_item”标志进行测试。该方法已经在我的测试中有效。所以现在我将所有记录的 created_at 和 published_at 字段设置为 1 个月前,然后想在一个数组中设置几个要在昨天发布的。

我使用以下代码设置所有然后 1 条记录:(在 Rails 3.1.1 中)

yesterday = Time.now - 1.day
last_month = Time.now - 1.month
Item.update_all(:created_at => last_month, :published_at => last_month)
Item.visible[1].update_attributes(:created_at => yesterday, :published_at => yesterday)

哪个有效。但是,如何在该数组中选择多个记录,而不仅仅是 [1] 索引。 IE。 [1,4,5,8,10] 等

我相信 update_attributes 不适用于多条记录。而且我不确定如何在现有数组中选择多个索引。

我希望这是有道理的......

提前致谢,

亚当。

【问题讨论】:

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


    【解决方案1】:

    update_attributes 是一个实例方法,即它将在模型的实例上工作。 update_all 是一个标准方法(可能是模型类委托给标准)并且可以链接到 mongoid 标准。如果您有一些标准来获取数组上文档的索引,您可以这样做:

    Item.visible.where(:some_other_field => "some_other_value").
        update_all(:created_at => last_month, :published_at => last_month)
    

    如果您没有标准,但正在挑选物品,您可以这样做:

    # instead of `model_array.update_attributes`
    ids = model_array.map(&:id)
    Item.all.for_ids(ids).update_all(:created_at => last_month, :published_at => last_month)
    

    【讨论】:

    • 感谢 Rubish 的建议...我可以看到它如何适用于范围。我认为我的问题更多是如何通过数组中的索引选择多个实例。就像选择[1,3,9]说的,编辑集合中的第1、3、9条记录。
    猜你喜欢
    • 2014-11-02
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    相关资源
    最近更新 更多