2016-03-02 83 views
1

Beginner rails error我試圖發送電子郵件給所有當前用戶,當文章更新。Rails ActionMailer error undefined email

我有sendgrid和設計與我的應用程序設置,並能夠讓郵件工作通過rails控制檯。但是,由於某種原因,我在更新文章時收到undefined method email for #<User::ActiveRecord_Relation:0x007f8685aebec0>

ArticleNotificationMailer

class ArticleNotificationMailer < ApplicationMailer 
     default from: '[email protected]' 

     def new_article(user, article) 
     @user = user 
     @article = article 

     mail(
      to: @user.email, 
      subject: "New update to article #{article.title}" 
     ) 
     end 
    end 

new_article.html.erb

<!DOCTYPE html> 
    <html> 
     <head> 
     <meta content="text/html; charset=UTF-8" http-equiv="Content-type" /> 
     </head> 
     <body> 
     <h1>New article on website "<%= @article.title %>"</h1> 
     <p> 
      <%= @article.body %> 
     </p> 
     <p> 
      <%= link_to "View Comment on site", article_url(@article, anchor: "updates=#{@article.id}") %> 
     </p> 
     </body> 
    </html> 

ArticleController 我使用ArticleNotificationMailer.new_article(@user, @article).deliver

 def update 
     respond_to do |format| 
      if @article.update(article_params) 
      ArticleNotificationMailer.new_article(@user, @article).deliver 
      format.html { redirect_to @article, notice: 'Article was successfully updated.' } 
      format.json { render :show, status: :ok, location: @article } 
      else 
      format.html { render :edit } 
      format.json { render json: @article.errors, status: :unprocessable_entity } 
      end 
     end 
     end 

錯誤消息

NoMethodError in ArticlesController#update 
undefined method `email' for #<User::ActiveRecord_Relation:0x007f8685aebec0> 

mail(
    to: @user.email, 
    subject: "New post to articles #{article.title}" 
) 
end 

的Rails控制檯

>> u = User.last 
>> a = Article.first 
>> ActionNotificationMailer.new_article(u, a).deliver_now 

回答

0

我想出瞭如何解決這個問題。

我將下面的代碼添加到article.rb並添加了@ article.send_notifications!到我的更新控制器。

def send_notifications! 
user = User.all 
user.each do |user| 
    ArticleNotificationMailer.new_article(user, self).deliver_now 
end 
end 
1
ArticleNotificationMailer.new_article(@user, @article).deliver 

好像@user通過User.where()在控制器初始化。 User.where返回實例User :: ActiveRecord_Relation這實際上是rails增強型數組。當您嘗試在此陣列上撥打電子郵件時會出現錯誤。

只要使用User.find如果您只需要查找一條記錄。

0

嘗試傳入元素的id。

class ArticleNotificationMailer < ApplicationMailer 
     default from: '[email protected]' 

     def new_article(user_id, article_id) 
     @user = User.where(id: user_id) 
     @article = Article.where(id: article_id) 

     mail(
      to: @user.email, 
      subject: "New update to article #{article.title}" 
     ) 
     end 
    end 


In your console 
>> u = User.last 
>> a = Article.first 
>> ActionNotificationMailer.new_article(u.id, a.id).deliver_now