Reputation: 349
I want the user to be able to send no more than 5 emails a day. Is it possible to validate that?
user_mailer.rb
class UserMailer < ActionMailer::Base
def contact_email(from_email, body, to_email)
@body = body
@user = User.find_by(email: to_email)
mail(from: from_email, to: to_email, subject: '', cc: from_email)
end
end
users_controller.rb
def send_mail
@user = User.find(params[:id])
@body = params[:message]
UserMailer.contact_email(current_user.email, @body, @user.email).deliver_now
end
Upvotes: 1
Views: 143
Reputation: 4322
You can create a model SentMail
with user_id
and created_at
.
Modify your User
model to include has_many :sent_mails
Then modify your send_mail
method as follows.
def send_mail
@user = User.find(params[:id])
@body = params[:message]
if @user.sent_mails.last_day.count < 5
UserMailer.contact_email(current_user.email, @body, @user.email).deliver_now
@user.sent_mails.create
end
end
In your SentMail
model create a scope last_day
that creates the following query where(created_at: 24.hours.ago..DateTime.now.utc)
The SentMail
model is also a good way to track the emails sent out and would be good if you want to store the state of the email if it was opened, delivered, clicked, etc..
Upvotes: 1