简体   繁体   English

Ruby on Rails-在Rake任务中从数据库获取用户电子邮件

[英]Ruby on Rails - Get user email from database in a Rake Task

I have that Mailer method and a Rake task to later scheduled with Cron Job and automate with Gem Whenever for send a email to a users: 我有那个Mailer方法和一个Rake任务,以后可以与Cron Job计划在一起,并与Gem每当需要时自动执行发送电子邮件给用户的操作:

# Mailer:

class MailCourseWarnMailer < ActionMailer::Base
  def course_available(user)
    @user = user
    mail(to: @user.email, subject: "Curso disponível")    # ... email sending logic goes here
  end
end

# Task
require 'rake'
desc 'send digest email'
task :send_warn_course, [:user_email] => :environment do |t, args|
  user = MailCourseWarn.find_by_email args[:user_email]
  MailCourseWarnMailer.course_available(user).deliver!
end

# Model 
class MailCourseWarn < ActiveRecord::Base
  belongs_to :course

  validates :name, :email, presence: true

end

I am currently run the task like this: rake send_warn_course['user@email.com'] but I need that this be automatic, in a way that when run rake send_warn_course the Rake Task send to all of users in my DB. 我目前正在运行这样的任务: rake send_warn_course['user@email.com']但我需要做到这一点,因为在运行rake send_warn_course时,Rake任务会发送给数据库中的所有用户。

Any ideas How can I do that? 有什么想法我该怎么做? Thanks. 谢谢。

Find the user(s) that need the email and iterate over them. 查找需要电子邮件的用户并对其进行遍历。 Surely you're indicating which users need the email in the database somehow, so you'll just want to query all those user records, iterate over them, and then send the email. 当然,您正在以某种方式指示哪些用户需要数据库中的电子邮件,因此您只想查询所有这些用户记录,遍历它们,然后发送电子邮件。

task :send_warn_course, [:user_email] => :environment do |t, args|
  MailCourseWarn.where(needs_warned: true).each do |user|
    MailCourseWarnMailer.course_available(user).deliver!
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM