2016-03-29 217 views
1

我正嘗試將多個電子郵件發送給多個品牌。我試圖在改變郵件收件人的電子郵件的同時多次運行這個循環,但它只會發送到最後的郵件請求。我將如何去解決這個問題?這裏是我當前的代碼:導軌發送多封電子郵件?

@user_products.each do |p| 
    @brands << p.brand 
end 
count = 0 
@brands = @brands.uniq 
while count < @brands.count 
    debugger 
     @brand = @brands[count] 
      mail(to: @brands[count].email, subject: 'A purchase has been made!') 
      count += 1 
    end 

我的HTML代碼來獲取產品由某品牌製造:

<body style="margin-left: auto; margin-right: auto; background-color: #d55d5d; width: 75%;"> 
    <div align="center"> 
     <img src="http://localhost:3000/assets/motobanner-d2fde8a6e30060905a6f72b0c8128d222a7596e690a7a4c648e5e81109bf4600.jpg" style="margin-top: 0% ;width: 75%; height: 240px;" ></img> 
    </div> 
    <div align="center"> 
     <h2>Hello, <%= @brand.name %>!</h2> 
      <p style="font-size: 1.2em;">There has been a purchase of the following items:</p> 
      <% @user_products.each do |item| %> 
       <div align="center"> <%= image_tag "http://localhost:3000/#{item.picture.url}", alt: item.product_name if item.picture && item.brand_id == @brand.id %><br /></div> 
       <b><%= "Product name:" if item.brand_id == @brand.id %></b> <%= item.product_name if item.brand_id == @brand.id %> 
       <b><%= "Product description:" if item.brand_id == @brand.id %></b><br /> <p class="product-description"><%= item.product_description if item.brand_id == @brand.id %></p> 
       <b><%= "Product price:" if item.brand_id == @brand.id %></b> <%= "£" + item.product_price.to_s if item.brand_id == @brand.id %> 
      <% end %> 
</body> 

我的電子郵件調試器是存在的,因爲我通過循環運行,它跑了每當它循環時,它都會出現mail(to: @brands[count].email, subject: 'A purchase has been made!')行,這就是爲什麼我不明白爲什麼它不起作用。

+0

如果我正確地記住它,郵件對象有一個發送方法 我想是發生的事情是,你有效地構建所有這些郵件,但軌道只發送最後一個給你,因爲它是一個那是最後返回的。 – Sidewinder94

+0

啊我明白了,是否會有更好的方式來執行此操作? –

回答

1

你應該做的郵包外循環,在正式例如:

class SendWeeklySummary 
    def run 
    User.find_each do |user| 
     UserMailer.weekly_summary(user).deliver_now 
    end 
    end 
end 

爲解釋在這裏:http://guides.rubyonrails.org/action_mailer_basics.html 和你可能缺少deliver_now部分(可通過deliver_later更換和工人進行過程

相關問題