我想知道当在inherited_resources框架中创建或更新记录时,发送电子邮件的最佳方式是什么。
现在我正在做这个:
def create
create!
UserMailer.create(object).deliver if @user.valid?
end
def update
update!
UserMailer.update(object).deliver if @user.valid?
end
这是有意义的,但似乎有点笨拙。我试着在成功响应块中这样做,但这似乎也是一件坏事。我还尝试链接到update_resource和create_resource方法。它们都可以工作,但是它们看起来都不是很优雅。
也许我试图尽量减少代码太多!
我更喜欢DDD方法,使用ActiveRecord回调
所以,如果你想在每次保存模型Example
后发送一封电子邮件,你应该这样做
class Example < ActiveRecord::Base
after_save :send_email
protected
def send_email
UserMailer.create(object).deliver
end
end
这是我目前正在做的。对我来说,这是最好的和更少混淆的方法:
after_filter :send_create_email, :only => :create
after_filter :send_update_email, :only => [:update, :update_password]
private
def send_create_email
UserMailer.create(@user).deliver if @user.valid?
end
def send_update_email
UserMailer.update(@user).deliver if @user.valid?
end
nathan的方法很好,直到我需要非标准的方法名。
我更喜欢这种方法:
def create
if @user.save # if your user is saved it should be valid
do something
else
do something else
end
end
def update
if @user.update_attributes(params[:user])
do something
else
do something else
end
end
您可以重构电子邮件的发送并使用after过滤器。在这种情况下,除非修改它们的默认行为,否则create和update都可以被删除。未经测试,但这是思路:
after_filter :send_email, :only => [ :create, :update ]
private
def send_email
UserMailer.send(request[:action].to_sym, @user).deliver if @user.valid?
end
我认为覆盖create_resource
是一个好方法:
# Responsible for saving the resource on :create method. Overwriting this
# allow you to control the way resource is saved. Let's say you have a
# PassworsController who is responsible for finding an user by email and
# sent password instructions for him. Instead of overwriting the entire
# :create method, you could do something:
#
# def create_resource(object)
# object.send_instructions_by_email
# end
#
def create_resource(object)
object.save
end
可以是这样的:
ActiveAdmin.register SomeModel do
controller do
def create_resource(object)
# TODO
end
end
end