通过电子邮件发送给讨论主题发表评论的所有用户

时间:2012-02-02 16:00:28

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我在这上花了几个小时,但我无法得到它:

我想做的是;发送新评论时,向所有在讨论区发表评论的用户发送电子邮件。

我正在使用 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

我将UserMailer.new_post_from_buyer(@ post).deliver正确放入posts_controller.rb

因此,有一些事情必须发生,我无法在我的生活中成功地工作。

1 - 我必须让所有帖子的用户与当前项目匹配。 (澄清一下,一个项目包含一个讨论板,其中所有帖子都去了)邮件程序中的当前代码为“帖子”抛出了一个未定义的方法,而我尝试的其他方式都不起作用。

2 - 然后我必须接受这些用户并提取他们的电子邮件(这是Users表中的一列)

3 - 然后我需要把他们所有的电子邮件转换成一个用逗号分隔的数组,这样我就可以把它放在user_mailer.rb的:bcc中。

你会如何让这个工作?使用.map或某种我不知道的方法的新方法,修复我认为需要的代码?

我正在运行Rails 3.1。

进一步澄清:

  • 用户has_many帖子。
  • 项目has_many帖子。
  • 发布belongs_to用户。
  • 发布belongs_to Project。

2 个答案:

答案 0 :(得分:3)

这可能不是最有效的方法,因为通常使用数据库命令梳理数据会更好,但根据你的模型和关系,你可以使用ruby方法做这样的事情:

def new_post_from_buyer(post)
  # This assumes that the attribute on the user that holds the email is called 'email'
  array_of_user_emails = post.project.posts.map { |pos| pos.user.email }
  mail(:to        => 'support@freelancify.com',
       :bcc       => array_of_user_emails,
       :subject   => 'The Project Poster Posted A New Comment')
end

我认为你的尝试也在正确的轨道上,只是语法错误。这可能实际上更有效:

def new_post_from_buyer(post)
  # This assumes that the attribute on the user that holds the email is called 'email'
  array_of_user_emails = User.includes(:posts).select(:email).where('posts.project_id = ?', post.project_id).map(&:email)
  mail(:to        => 'support@freelancify.com',
       :bcc       => array_of_user_emails,
       :subject   => 'The Project Poster Posted A New Comment')
end

这可能比我的第一个例子更有效,因为它使用SQL来搜索电子邮件。只有在将ActiveRecord与基于SQL的数据库一起使用时,这才有效。

答案 1 :(得分:1)

尝试:

def new_post_from_buyer(post)
  @post = post
  posts = Post.where(:project_id => post.project_id)
  @users = []
  posts.each do |p|
    @users << p.user.email
  end
  mail(:to        => 'support@freelancify.com',
       :bcc       => @users
       :subject   => 'The Project Poster Posted A New Comment')
end

这将生成一个包含该项目帖子的所有用户的数组。

如果你想从该数组创建一个字符串,我相信你只需要做@users.join(',')

编辑:将代码插入方法