たとえば、私には2つのモデルがあります
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)