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 获取有效值的机会很小,因为我猜它是由rails 通过has_and_belongs_to_many 关系动态填充的。

所以我的问题是:

如何在更新发生之前获取所有相关用户?

(到目前为止我尝试过的其他一些事情:)

A. 在 DocumentController::edit 中获取 document.users.all。这将返回一个有效的数组,但是我不知道如何将此数组传递给 DocumentObserver.after_update 以执行计算(只是在 DocumentController 中设置一个实例变量当然是行不通的)

B. 试图将 document.users 保存在 DocumentObserver::before_update 中。这也不起作用。我仍然得到新的用户价值

提前致谢

乔治

红宝石 1.9.2p320

导轨 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 回答