I spent hours on this and I just cannot get it:
What I am trying to do is; email all users who have made a comment on a discussion board whenever a new comment is posted.
I am using user_mailer.rb
def new_post_from_buyer(post)
@post = post
users = User.all.posts.where(:project_id => post.project.id)
mail(:to => 'support@freelancify.com',
:bcc => #Somehow turn the users variable i just named into an array of their emails
:subject => 'The Project Poster Posted A New Comment')
end
I have the UserMailer.new_post_from_buyer(@post).deliver correctly placed in the posts_controller.rb
So there’s a few things that has to happen which I cannot for the life of me get to work successfully.
1 – I have to get all the Users who’s Posts match the current Project. (to clarify, a Project contains a discussion board in which where all the posts go) The current code in the mailer throws a undefined method for ‘posts’, and every other way I tried won’t work.
2 – I then have to take those Users and extract their emails (which is a column in the Users table)
3 – I need to then be able to take all their emails and turn it into an array separated by commas so I can throw it in the :bcc of the user_mailer.rb.
How would you go about getting this to work? A new way with .map or some method I have no idea about, fixing up the code I think I need?
I am running Rails 3.1.
To further clarify:
- User has_many Posts.
- Project has_many Posts.
- Post belongs_to User.
- Post belongs_to Project.
This may not be the most efficient way to do it, as it is generally better to use database commands to comb data, but based on your models and relationships you could use ruby methods to do something like this:
I think you were also on the right track in your attempt, just with wrong syntax. This might actually be a little more efficient:
This would probably be even more efficient than my first example since it uses SQL to do the searching for the email. This would only work if you were using ActiveRecord with a SQL based database.