比方说,我有两个模型
class User
embeds_many :notifications
field :age, type :Integer
class Notification
embedded_in :user
field :message, type: String
我想创建通知并将其添加到所有用户,匹配特定条件。我想出的只是:
notification = Notification.new
notification.message = "Hello"
User.where(:age.ge => 18).push(:notifications, notification)
但这行不通。任何的想法?
UPD:我知道,有办法让它像这样工作:
users = User.where(:age.ge => 18)
users.each do |user|
notification = Notification.new
notification.message = "Hello"
user.notifications << notification
user.save
end
但这似乎是丑陋且低效的代码。
UPD2:最后,此代码可以直接与驱动程序一起使用,如 Winfield 所述:
users = User.where(:age.ge => 18)
notification = Notification.new
notification.message = "Hello"
User.collection.update(users.selector, {'$push' => {notifications: notification.as_document}}, multi: true)