Sonny Black
Sonny Black

Reputation: 1617

How to limit the number of emails sent (ActionMailer) per subscriber

So I have a newsletter application, however, it's not working correctly.

How it's supposed to work is a subscriber chooses a category to subscribe to and receives one quote about that category a day. So if you subscribe to fitness category, you'll receive one new fitness quote each day.

In my case, if you subscribe to fitness you'll receive all of the quotes associated with the fitness category in one shot.

See my code below:

 Category.all.each do |category|
   category.subscribers.each do |subscriber|
      category.quotes.each do |quote|
       SubscriptionMailer.sendmyemail(subscriber.email, category, quote.body, category.subscribers).deliver
     end
    end
end

How can I send the one quote allotment to each subscriber, that's relevant to the category they chose, without sending every quote associated with each category all at once. I see it as, there's an array of quotes associated with the categories, how can I send only one new quote each day that corresponds with the subscribers category?

Upvotes: 0

Views: 692

Answers (1)

Pramod Solanky
Pramod Solanky

Reputation: 1690

The code below sends the first Quote to its subscriber. Of course You have to maintain a table or a field that keeps of track of what quotes were sent earlier to the subscriber so you can always manage to send a new quote every day.

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

This can further be updated to:

Category.all.each do |category|
   category.subscribers.each do |subscriber|
      SubscriptionMailer.sendmyemail(subscriber.email, category, subscriber.choose_quote(category), category.subscribers).deliver          
   end
end    

And in your model,

def choose_quote(cat)
  # send quote which is unique 
  # Meaning which was not sent 
end

This gives you an idea as to how to go ahead with this, code is not tested and its just for reference

Upvotes: 1

Related Questions