2012-02-02 93 views
0

我在這個上花了幾個小時,而我卻不明白:發送電子郵件給討論主題發表評論的所有用戶

我在做什麼;只要發佈新評論,即可通過電子郵件向在論壇上發表評論的所有用戶發送電子郵件。

我使用user_mailer.rb

def new_post_from_buyer(post) 
    @post = post 
    users = User.all.posts.where(:project_id => post.project.id) 
    mail(:to  => '[email protected]', 
     :bcc  => #Somehow turn the users variable i just named into an array of their emails 
     :subject => 'The Project Poster Posted A New Comment') 
end 

我.deliver正確安放在posts_controller.rb的UserMailer.new_post_from_buyer(@post)

所以這是有幾件事情要發生,我不能爲我的生活成功地工作。

1 - 我必須讓所有帖子與當前項目相匹配的用戶。 (爲了澄清,一個項目包含一個討論區,其中所有帖子都放在該討論區)郵件程序中的當前代碼拋出'posts'的未定義方法,並且我嘗試過的其他所有方法都不起作用。

2 - 然後我必須採取那些用戶和提取他們的電子郵件(這是在用戶表中的列)

3 - 我需要然後能夠採取其的所有電子郵件並把它變成一個數組以逗號分隔,所以我可以將它放在user_mailer.rb的:bcc中。

你將如何去實現這個工作?一個新的方式與.map或一些我不知道的方法,修復我認爲我需要的代碼?

我正在運行Rails 3.1。

爲了進一步闡明:

  • 用戶的has_many帖子。
  • 項目has_many文章。
  • 發佈belongs_to用戶。
  • 發佈belongs_to項目。

回答

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  => '[email protected]', 
     :bcc  => array_of_user_emails, 
     :subject => 'The Project Poster Posted A New Comment') 
end 

我想你也分別在正確的軌道上你嘗試,j錯誤的語法。這實際上可能是多一點效率:因爲它使用SQL做搜索的電子郵件

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  => '[email protected]', 
     :bcc  => array_of_user_emails, 
     :subject => 'The Project Poster Posted A New Comment') 
end 

這可能甚至比我的第一個例子更有效率。這隻有在您將ActiveRecord與基於SQL的數據庫結合使用時纔有效。

+0

謝謝..我認爲| pos | pos.user.email假設包含't'。你的解決方案工作謝謝你好奇;當它創建一個數組時,它是否用逗號分隔每個電子郵件? – 2012-02-02 16:17:56

+0

@JamesF - 它可能包括't',但它不必。在這種情況下,我實際上故意省略了't',因爲該方法的參數名爲'post',即使我不認爲在map方法中會有內容(因爲它位於它自己的塊中) ,我不想冒任何變量名稱衝突的風險。你可以把它改成像'| a_post |'或者甚至是'post'這樣的東西,就像你建議的更清晰一樣,我只是想確保我使用不同的變量名稱來避免名稱衝突和讀取時的清晰度。 – Batkins 2012-02-02 16:23:47

+0

另外,我會建議試用Ruby的'map'方法,直到你掌握它爲止,這是非常有用的,並且還將幫助你理解ruby各種ruby方法如何與'block'語句一起工作。 [這是一個鏈接到'map'方法的文檔](http://ruby-doc.org/core-1.9.3/Array.html#method-i-map)。 – Batkins 2012-02-02 16:27:17

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  => '[email protected]', 
     :bcc  => @users 
     :subject => 'The Project Poster Posted A New Comment') 
end 

這將產生所有誰擁有該項目後的用戶的數組。

如果你想創建這個數組一個字符串,我相信你會需要做的僅僅@users.join(',')

編輯:插入的代碼添加到方法

+0

嗨。我會在哪裏實施這個?我不太確定。我會把什麼放在:密件抄送區?我需要關閉'做',對吧? – 2012-02-02 16:13:07

+0

@JamesF剛編輯它將其包含在方法中。而且,我忘了關閉循環 – TheDude 2012-02-02 16:17:00

+0

嘿Bwalks,謝謝你的答案。我決定使用.map答案,因爲我需要親自處理它。我還是把你錄下來。 – 2012-02-02 16:30:36

相關問題