2

私のアプリケーションでは、次の関係があります。

Document has_and_belongs_to_many Users
User has_and_belongs_to_many Documents

私が理解しようとしているのは、次のことを実行する方法です。ドキュメントに3人のユーザーが属しているとします。更新後、それらは元になります。4、最初の3つに電子メールメッセージ(document_updated)を送信し、4番目に別の電子メールメッセージ(document_assigned)を送信したいと思います。

したがって、ドキュメントの更新が行われる前と後に、自分のドキュメントに属するユーザーを知る必要があります。

これまでの私のアプローチは、次のようなオブザーバーを作成することでした。

class DocumentObserver < ActiveRecord::Observer

  def after_update(document)
    # this works because of ActiveModel::Dirty
    # @old_subject=document.subject_was    #subject is a Document attribute (string)

    # this is not working - I get an 'undefined method' error 
    @old_users=document.users_was   

    @new_users=document.users.all.dup

    # perform calculations to find out who the new users are and send emails....
  end
end

@old_usersが有効な値を取得する可能性は低いことを知っていました。これは、has_and_belongs_to_many関係を介してrailsによって動的に入力されると推測されるためです。

だから私の質問は:

更新が発生する前に、関連するすべてのユーザーを取得するにはどうすればよいですか?

(私がこれまでに試した他のいくつかのこと:)

A. DocumentController::edit内でdocument.users.allを取得します。これは有効な配列を返しますが、計算を実行するためにこの配列をDocumentObserver.after_updateに渡す方法がわかりません(もちろん、DocumentController内にインスタンス変数を設定するだけでは機能しません)

B. DocumentObserver::before_update内にdocument.usersを保存しようとしています。これも機能していません。私はまだ新しいユーザー値を取得します

前もって感謝します

ジョージ

Ruby 1.9.2p320

Rails 3.1.0

4

1 に答える 1

0

before_addコールバックを使用できます

class Document
  has_and_belongs_to_many :users, :before_add => :do_stuff

  def  do_stuff(user)
  end
end

ドキュメントにユーザーを追加すると、そのコールバックが呼び出され、その時点でも、self.users追加するユーザーが含まれています。

より複雑なものが必要な場合は、set_usersドキュメントにメソッドを設定する方が簡単な場合があります

def set_users(new_user_set)
  existing = users
  new_users = users - new_user_set
  # send your emails
  self.users = new_user_set
end
于 2012-05-27T08:37:53.627 に答える