Question

I have a blog, which has a model for commenting on each post. I have a mailer set up so that the author of the post gets an email alert when someone has commented on their post. What I want to do now is make an email alert that will go out to every other user that also commented on that one post. I think I would need an if/then statement, but I haven't quite figured it out yet.

Here is my controller when posts are created:

def create
@post = Post.find(params[:post_id])
@blog_comment = @post.blog_comments.create(params[:blog_comment])
@blog_comment.user = current_user

respond_to do |format|
  if @blog_comment.save
    format.html { redirect_to @post, notice: 'Blog comment was successfully created.' }
    format.json { render action: 'show', status: :created, location: @blog_comment }
  else
    format.html { render action: 'new' }
    format.json { render json: @blog_comment.errors, status: :unprocessable_entity }
  end
end

Here is my mailer:

def blog_comment(user)
@user = user
mail(to: [user.email],
    bcc: ['user@example.com'],
   from: 'user@example.com',
subject: 'Hi from theTens!')
end

In the models: Each post has_many blog_comments, the posts belongs_to user, the blog_comments belong_post and belong_to user

Was it helpful?

Solution

I finally came up with a solution. Here is my code that I wrote for inside the "create" method in my comments controller:

respond_to do |format|
  if @comment.save
    format.html { redirect_to @post, notice: 'Comment was successfully created.' }
    format.json { render json: @comment, status: :created, location: @comment }

    @commenter = @post.comments.collect(&:user)
    @commenter = @commenter.uniq

    @commenter.each do |commenter|  
      MyMailer.commenter_email(commenter).deliver
    end  

  else
    format.html { render action: "new" }
    format.json { render json: @comment.errors, status: :unprocessable_entity }
  end
end

So @commenter is collecting an array of all of the users who commented on that post. I then had to make @commenter equal @commenter.uniq so that when a user comments 3 times on a post, they don't get three emails whenever someone else comments.

Then I just made a mailer view and a commenter_email method in my_mailer.rb

The only issue is that it if you are the first person who comments, you'll get an email too, since I included the mailer after the "save" in the controller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top