Search code examples
ruby-on-railsrubymvcmailer

How sending emails to users authorised to view a post - polymorphic association Ruby-on-Rails


Using polymorphic association, I was able to give specific users access to edit a particular post.

My model looks like this

User model

has_many :postuser
has_many :posts, through: :postuser

Post model

has_many :postuser
has_many :users, through: :postuser

post user

belongs_to :post
belongs_to :user

I want to send all users authorised to view a post whenever the post is updated.

In my model_mailer I have

class ModelMailer < ApplicationMailer
  def new_user_notification(post)
    @post = post
    mail to: @Post.postuser.user.email, subject: "Welcome User"
  end
end

but I am getting

undefined method `postuser' 

how do I send mails to only users related via postusers.


Solution

  • if you want to send email once a post is updated, you can simply do something like this.

    def new_record_notification(post, current_user_email)
      @post = post
      @current_user_email = current_user_email  
      users_email = post.postusers.map{|post| post.user.email}.join(",")
      mail to: users_email, subject: "Your post has been updated"
    end
    

    and then you can have this in your update method in the post controller

    ModelMailer.new_record_notification(@project, current_user.email).deliver_now