如何通过Action Mailer每天发送独特的消息

Son*_*ack 0 ruby ruby-on-rails actionmailer ruby-on-rails-4

所以我有一份时事通讯,但是我无法想出一种方法来跟踪已发送的报价.我想跟踪发送的报价以避免发送重复项.

应用程序非常简单,有一个属于类别模型的引用模型,以及属于类别模型的订阅者模型.类别has_many订阅者和引号.

下面的代码将第一个Quote发送给其订阅者.当然,您必须维护一个表或字段,以便跟踪之前发送给订户的报价,以便您始终可以设置每天发送新报价.

Category.all.each do |category|
   category.subscribers.each do |subscriber|
      SubscriptionMailer.sendmyemail(subscriber.email, category, category.quotes.first.body, category.subscribers).deliver          
   end
end
Run Code Online (Sandbox Code Playgroud)

这可以进一步更新为:

Category.all.each do |category|
   category.subscribers.each do |subscriber|
      SubscriptionMailer.sendmyemail(subscriber.email, category, subscriber.choose_quote(category), category.subscribers).deliver          
   end
end    
Run Code Online (Sandbox Code Playgroud)

在我的subscriber.rb模型中,我准备好了这个方法,但不确定用什么代码来填充它以实现我想要的.如何每天向订阅者发送一个独特的报价,而不是过去发送的报价的副本?或者甚至更简单的方法是随机化订单,这可能吗?

def choose_quote(cat)
  # send quote which is unique 
  # Meaning which was not sent 
end
Run Code Online (Sandbox Code Playgroud)

Rub*_*der 7

  • 您正在向订阅者发送报价
  • 您需要跟踪已发送给您的用户的报价.

我建议针对您提到的特定问题设计可能的解决方案.

rails generate model quote_history subscriber:references quote:references # assumed there
#is a model subscriber and quote
Run Code Online (Sandbox Code Playgroud)

所以现在subscriber_quote_history也属于订阅者和引用.

class QuoteHistory < ActiveRecord::Base
  belongs_to :subscriber
  belongs_to :quote
  validates :quote_id, :uniqueness => {scope: :subscriber_id}
end
Run Code Online (Sandbox Code Playgroud)

因此,订阅者,报价应该有很多quote_histories他们已被发送.

class Subscriber < ActiveRecord::Base
   has_many :quote_histories
   .....
end

class Quote < ActiveRecord::Base
   has_many :quote_histories
   scope :uniq_quote_for, Proc.new {|subscriber_id| includes(:quote_histories).where.not(quote_history: {subscriber_id: subscriber_id})}
   .....
end
Run Code Online (Sandbox Code Playgroud)

现在我建议你用你想要的方法写一些条件:

class Subscriber < ActiveRecord::Base
 def choose_quote(cat)
   quote = cat.quotes.uniq_quote_for(self.id).order("RANDOM()").first #Add a new history after that for that. here you will decide your own business logic.
   return quote if self.quote_histories.create(qoute_id: quote.id)
   return nil
 end
end
Run Code Online (Sandbox Code Playgroud)

在你的邮件程序中做类似的事情:

Category.all.each do |category|
   category.subscribers.each do |subscriber|
      quote = subscriber.choose_quote(category)
      if quote  # if quote found then send email
       SubscriptionMailer.sendmyemail(subscriber.email, category, quote, category.subscribers).deliver    
      else
        next # if no quote found then go to next loop.
      end      
   end
end  
Run Code Online (Sandbox Code Playgroud)

我相信这有助于您设计解决方案.请注意,我在这里写了一切来自可视化和我自己的逻辑.请跳过一些不需要的传统错误或任何内容 我的目的是向您展示解决问题的方法.

谢谢.