【问题标题】:How sending emails to users authorised to view a post - polymorphic association Ruby-on-Rails如何向有权查看帖子的用户发送电子邮件 - 多态关联 Ruby-on-Rails
【发布时间】:2020-12-07 16:12:22
【问题描述】:

使用多态关联,我能够授予特定用户编辑特定帖子的权限。

我的模型是这样的

用户模型

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' 

如何仅向通过 postusers 相关的用户发送邮件。

【问题讨论】:

  • 顺便说一句:has_many :postusers
  • 我不明白。
  • postuser 是单数,正如@benjessop 指出的那样,您可能希望将 has_many 更改为 :postusers。并在其他任何地方进行更改。
  • 正如@benjessop 提到的,在用户模型和后期模型中都应该是has_many :postures。因为post有很多postuser。当您致电@post.postusers 时,您将获得所有姿势的数组。因此,您必须遍历姿势以获取单个用户` postusers = @post.postusers`,然后您可以遍历姿势
  • 是您的模型名称PostUserPostuser 吗?

标签: ruby-on-rails ruby mvcmailer


【解决方案1】:

如果您想在帖子更新后发送电子邮件,您可以简单地执行以下操作。

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 控制器的更新方法中使用它

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

【讨论】:

    【解决方案2】:

    这里有一个快速修复:

    用户.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
    

    【讨论】:

      猜你喜欢
      • 2015-06-15
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 2012-08-14
      • 2016-07-04
      • 2016-12-18
      • 2023-03-28
      相关资源
      最近更新 更多