在 rake 任务期间关闭观察者的简单方法?
我在我的应用程序中使用restful_authentication。 我正在使用 rake 任务创建一组默认用户,但每次运行该任务时,都会发送一封激活电子邮件,因为观察者与我的用户模型关联。 我在创建用户时设置激活字段,因此不需要激活。
有人知道在运行 rake 任务时绕过观察者的简单方法,以便在保存用户时不会发送电子邮件吗?
谢谢。
I'm using restful_authentication in my app. I'm creating a set of default users using a rake task, but every time I run the task an activation email is sent out because of the observer associated with my user model. I'm setting the activation fields when I create the users, so no activation is necessary.
Anyone know of an easy way to bypass observers while running a rake task so that no emails get sent out when I save the user?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
Rails 3.1 最终为此提供了 API:
http://api.rubyonrails.org/v3 .1.0/classes/ActiveModel/ObserverArray.html#method-i-disable
其中
ORM
可以是ActiveRecord::Base
Rails 3.1 finally comes with API for this:
http://api.rubyonrails.org/v3.1.0/classes/ActiveModel/ObserverArray.html#method-i-disable
Where
ORM
could for example beActiveRecord::Base
作为观察者的标志,我喜欢定义一个名为“disabled”的类访问器,因此它的读法如下:
我将其作为敏感回调中的条件
,然后在需要时打开该标志
As a flag for the observer I like to define a class accessor called "disabled" so it reads like this:
I put it as a condition in the sensitive callbacks
and I just turn the flag on when needed
您可以向用户模型添加一个访问器,例如“skip_activation”,不需要保存,但会在整个会话中持续存在,然后检查观察者中的标志。 然后
,在观察者中:
You could add an accessor to your user model, something like "skip_activation" that wouldn't need to be saved, but would persist through the session, and then check the flag in the observer. Something like
Then, in the observer:
您可以尝试另一种(rails 3)
Another one you can try (rails 3)
一般来说,对于这些类型的情况,您可以:
在这种情况下,我想说#3 是你最好的选择。
In generally, for these sorts of situations, you can:
In this case, I'd say #3 is your best bet.
在我正在开发的应用程序上运行测试时,我使用以下内容:
When running tests on an app I am working on, I use the following:
禁用 Rails 3 的观察者很简单:
Disabling observers for Rails 3 it's simple:
你可以把这个方法从观察者身上拿走;
将通过删除它来停止 MessageObserver 上的 :after_create 。
You can take the method off the observer;
Will stop the :after_create on MessageObserver by removing it.
我来这里寻找相同的答案...以上似乎都没有解决问题(或者涉及向我的应用程序代码添加特定于迁移的逻辑 - 嘘)。
这是我想到的(有点蹩脚,它需要进入每个相关的迁移,但是......)
I came here looking for the an answer to the same... none of the above seemed to do the trick (or involve adding migration-specific logic to my application code -- boo).
Here's what I came up with (a bit lame that it needs to go in each relevant migration, but...)
更多相关内容:
禁用 Rails 3 中的回调
More on this:
Disabling Callbacks in Rails 3
据我所知,没有一种简单的方法可以禁用观察者,但听起来可以向观察者添加逻辑,以便在设置激活码时不发送电子邮件......
There isn't a straightforward way to disable observers that I know of, but it sounds possible to add logic to your observer to not send an email when the activation code is set...
正如其他人所暗示的那样; 我会用一个简单的 if 语句将不需要的逻辑包装在观察者中。
As others have hinted; I would wrap the unwanted logic in your Observer with a simple if statement.