3

所以,我有这个网站,我已经建立了http://leapfm.com/并且越来越多的用户加入了这太棒了。我注意到用户重新登录以检查他们的歌曲是否已被投票。我想为他们自动化这个过程。

所以,我想实现一个功能,当他们的歌曲被投票时,它会向用户发送一封电子邮件。我不确定这是否可以专门用于我的堆栈。

例如,为了投票,我正在使用这个 gem

我可以实现这样的事情吗?如果您需要我提供任何其他信息,请不要害怕询问。

song_controller 片段(创建动作):

def create
    @song = Song.new(song_params)
    @song.user = current_user
    respond_to do |format|
      if @song.save
        format.html { redirect_to @song, notice: 'Song was successfully created.' }
        format.json { render action: 'show', status: :created, location: @song }
      else
        format.html { render action: 'new' }
        format.json { render json: @song.errors, status: :unprocessable_entity }
      end
    end
  end
4

1 回答 1

8

这应该是相当简单的。您想要做的是在每次创建投票记录时发送一封电子邮件。after_commit首先,在您的 Vote 模型中,您将在创建实例时设置一个处理程序。

class Vote
  ...
  after_commit :send_email, :on => :create

  def send_email
    # send the email to whoever owns votable
  end
end

# send the email零件内,有几个选项。最简单的方法是简单地配置 ActionMailer 并在该send_email方法中发送电子邮件。有几种设置方法。我最近使用的是Postmark,您可以为此安装postmark-rails并添加类似以下内容的config/environments/production.rb.

config.action_mailer.delivery_method = :postmark
config.action_mailer.postmark_settings = { :api_key => 'your-api-key' }

但是,我鼓励您查看各种提供商以找到适合您需求的提供商(我可以想到 Postmark、SendGrid、Mailgun)。

然后,运行rails generate mailer VoteMailer,它将在 下创建一个 VoteMailer 类app/mailers/vote_mailer.rb。编辑它以满足您的需求。

class VoteMailer < ActionMailer::Base
  default from: 'notifications@example.com'

  def vote_notification(voter, song)
    @voter = voter
    @song = song
    @user = @song.user
    mail(to: @user.email, subject: 'Someone voted on your song!')
  end
end

现在,您在app/views/vote_mailer/vote_notification.text.erb.

Hey <%= @user.name %>,

Someone voted on your song, <%= @song.name %>!

Congrats!

send_email然后,在您的方法中使用邮件程序。

class Vote
  ...
  def send_email
    VoteNotifier.vote_notification(voter, voteable).deliver!
  end
end

这应该让你开始。

人们早些时候评论说需要使用延迟作业。这是因为发送电子邮件可能是一个缓慢的过程。如果用户每次点击“upvote”,他们都必须等待 5 秒才能发送电子邮件,他们就会对服务不满意。

为了避免这个问题,人们会将他们的服务器请求中更耗时的部分放入一个作业队列中,然后由另一台服务器处理。要通过您的电子邮件实现此目的,您将安装delayed_job_active_record并更改您的send_email方法:

class Vote
  ...
  def send_email
    VoteNotifier.delay.vote_notification(voter, voteable)
  end
end

然后在服务器上的一个单独进程中,运行jobs:workRake 任务。

bundle exec rake jobs:work

该进程应该 24/7 全天候运行,就像您的 Web 服务器进程一样。

于 2013-08-22T18:58:34.433 回答