1

たとえば、私には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)
4

1 に答える 1

1

おそらく、生の Mongo Driver レベルでこれを行うことができます。

db.users.update({}, { $push: { notifications: { message: 'Hello!' } } })

ただし、大量メッセージ機能を実現することが目的の場合は、これらの通知用に特別なコレクションを作成し、アプリケーション コードでシステム全体の通知とユーザー ターゲット通知をプルする方がよい場合があります。

大量のメッセージを送信するためにシステム内のすべてのユーザー オブジェクトを更新する必要があるのは、スケーラブルな設計ではありません。

于 2012-12-19T15:47:31.403 に答える