[英]Rails ActionMailer error undefined email
初學者Rails錯誤我正在嘗試在文章更新時向所有當前用戶發送電子郵件。
我已經使用我的應用程序設置了sendgrid並設計了它,並且能夠使郵件程序通過Rails控制台工作。 但是,由於某種原因,在更新文章時,我收到undefined method email for #<User::ActiveRecord_Relation:0x007f8685aebec0>
的undefined method email for #<User::ActiveRecord_Relation:0x007f8685aebec0>
。
ArticleNotificationMailer
class ArticleNotificationMailer < ApplicationMailer
default from: 'you@example.com'
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
ArticleNotificationMailer.new_article(@user, @article).deliver
好像@user是由控制器中的User.where()初始化的。 User.where返回User :: ActiveRecord_Relation的實例,該實例實際上是rails增強的數組。 當您嘗試在此陣列上調用電子郵件時,會出現錯誤。
如果只需要查找一條記錄,只需使用User.find即可。
嘗試傳遞元素的ID。
class ArticleNotificationMailer < ApplicationMailer
default from: 'you@example.com'
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
我想出了解決方法。
我將以下代碼添加到article.rb,並添加了@ article.send_notifications! 到我的更新控制器。
def send_notifications!
user = User.all
user.each do |user|
ArticleNotificationMailer.new_article(user, self).deliver_now
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.