问题
I have a User model (with Devise), and a Post model that belongs to the user. I used this railscast (pro) to send the User an email after creating an account
I created a "NewPostMailer"
This is my mailer:
class NewPostMailer < ActionMailer::Base
default :from => "email@gmail.com"
def new_post_email(user)
@user = user
@url = "http://localhost.com:3000/users/login"
mail(:to => user.email, :subject => "New Post")
end
end
My posts_controller:
def create
@post= Post.new(params[:post])
respond_to do |format|
if @deal.save
NewPostMailer.new_post_confirmation(@user).deliver
format.html { redirect_to @post, notice: 'Post was successfully created.' }
post.rb
after_create :send_new_post_email
private
def send_new_post_email
NewPostMailer.new_post_email(self).deliver
end
What do I have to change to send the User an email after he creates a Post. Thanks.
回答1:
Create another mailer (http://railscasts.com/episodes/206-action-mailer-in-rails-3)
class YourMailerName < ActionMailer::Base
default :from => "you@example.com"
def post_email(user)
mail(:to => "#{user.name} <#{user.email}>", :subject => "Registered")
end
end
In your Post model
after_create :send_email
def send_email
YourMailerName.post_email(self.user).deliver
end
Sending an email is very slow so think about putting this in a background job.
回答2:
You should be able to use a fairly similar method to do this. First, create an after_create
callback in your Post
model, with something like:
after_create :send_user_notification
def send_user_notification
UserMailer.post_creation_notification(user).deliver
end
You will need to make sure that there is a relationship between the user and the post, and create the post_creation_notification
method in your UserMailer
, the same way you made your old one. It might also be worth pointing out that just blindly firing off emails like this isn't necessarily the best way to do this. Not only does it add extra unnecessary time to a request, but it also doesn't fail in a gracefully recoverable fashion. You may wish to explore adding the emails to be sent to a queue (like this, for example) to be processed, with a cron job or something, if the site you are creating will see anything other than very light usage.
来源:https://stackoverflow.com/questions/13755249/send-user-email-after-creating-a-post-with-action-mailer