问题
I have a Document model with a string column access and a User model with a string column team. In a Document I can enter an array of items for access such as "staff, sales, manager". Meanwhile, a User has only one item under team.
I am trying to send emails to specific Users based on whether or not for each user.team is included in the array for Document.access.
For example if Document.access = "sales, management"
, only Users with team = "sales" or team = "management"
will be sent the email. Other Users such as team = "accounting" would not.
Update:
From what I gather on this question, It would appear ActionMailer cannot loop, so I have modified my document_observer. Now that I moved the loop portion out of the mailer, user.email is erroring out with
undefined method 'user' for
If I stick in a string like 'joe@net.com' the proper number of emails go out, so that part seems to work. Now it is a matter of passing the right email addresses to the message.
Relevant code from my document_observer below:
def after_save(model)
@users = User.all
@users.each do |user|
if model.access.include? user.team
MultiMailer.doc_notification(model).deliver
end
end
end
Relevant code from mailer. How do I pass on user.email for each email?
def doc_notification(document)
mail(:to => 'joe@net.com')
end
Latest Update:
Ok, I just switched a couple of lines to
MultiMailer.doc_notification(user).deliver
and
def doc_notification(user)
So now the email goes out to each of the right users, but it appears I am just reversing the problem above and trading unknown user for unknown document. The email needs to reference the URL for the document that was just updated..
I should also mention that there is no association between Document and User.
回答1:
The Answer
From the document_observer
def after_save(model)
@users = User.all
@users.each do |user|
if model.access.include? user.team
MultiMailer.doc_notification(model, user).deliver
end
end
end
From the mailer
def doc_notification(document, user)
@document = document
mail(:to => user.email)
end
Credit goes to a very nice Nathaniel Talbott of Triangle Ruby Brigade who answered my question in person. I guess it helps to get out the house sometimes.
来源:https://stackoverflow.com/questions/13518352/rails-actionmailer-to-email-specific-group-of-users-based-on-user-attribute-bein