如何解决如何向有权查看帖子的用户发送电子邮件-多态关联Ruby-on-Rails
使用多态关联,我可以为特定用户提供编辑特定帖子的权限。
我的模特看起来像这样
用户模型
has_many :postuser
has_many :posts,through: :postuser
帖子模型
has_many :postuser
has_many :users,through: :postuser
发布用户
belongs_to :post
belongs_to :user
我想发送所有有权更新帖子的用户。
在我的model_mailer中,
class ModelMailer < ApplicationMailer
def new_user_notification(post)
@post = post
mail to: @Post.postuser.user.email,subject: "Welcome User"
end
end
但是我得到了
undefined method `postuser'
如何仅将邮件发送给通过postuser相关的用户。
解决方法
这是一个快速解决方法:
user.rb
has_many :postusers
has_many :posts,through: :postusers
post.rb
has_many :postusers
has_many :users,through: :postuser
postuser.rb
belongs_to :post
belongs_to :user
after_commit -> {
ModelMailer.new_user_notification(post,user).deliver_now # or deliver_later
},on: :create
model_mailer.rb
class ModelMailer < ApplicationMailer
def new_user_notification(post,user)
@post = post
mail to: user.email,subject: "Welcome User"
end
end
现在,每当您创建一个新的postuser时,after_create触发器将运行并为您的用户发送电子邮件。
我还建议您将模型更改为PostUser
,并使用post_users
的方式rails
。
rails g model post_user post:references user:references
,
如果您要在帖子更新后发送电子邮件,只需执行以下操作即可。
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
然后可以在post controller的update方法中使用它
ModelMailer.new_record_notification(@project,current_user.email).deliver_now
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。