开发者

Updating attributes on several indexes in array. Using mongoid in Rails 3

开发者 https://www.devze.com 2023-04-13 06:02 出处:网络
Inside my test database, I would like to trigger a \"new_item\" flag for testing.The method already works in my tests.So now I am setting the created_at and published_at fields of all records to 1 mon

Inside my test database, I would like to trigger a "new_item" flag for testing. The method already works in my tests. So now I am setting the created_at and published_at fields of all records to 1 month ago, then want to set a select few in an array to be published yesterday.

I use the following code to set all then 1 record: (In 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)

Which works. However, how can I select multiple records in that array instead of just the [1] index. ie. [1,4,5,8,10] etc.

I believe update_attributes doesn't work on multiple records. And I'm not sure how to select multiple indexes in an existing array.

开发者_JAVA百科

I hope this makes sense...

Thanks in advance,

Adam.


update_attributes is an instance method, i.e. it will work on an instance of the model. update_all is a criteria method(may be model class delegates to criteria) and can be chained to mongoid criteria. If you have some criteria for obtaining the indexes of documents on array you can do:

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

If you don't have a criteria, but are handpicking the items, you can do:

# 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号