Reputation: 592
Beginner rails error I'm trying to send emails out to ALL current users when an article is updated.
I have sendgrid and devise set up with my app and am able to get the mailer to work through rails console. But, for some reason, I receive an undefined method email for #<User::ActiveRecord_Relation:0x007f8685aebec0>
when updating an article.
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
I'm using 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
Error Message
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 Console
>> u = User.last
>> a = Article.first
>> ActionNotificationMailer.new_article(u, a).deliver_now
Upvotes: 1
Views: 66
Reputation: 592
I figured out how to fix this.
I added the code below to article.rb and added @article.send_notifications! to my update controller.
def send_notifications!
user = User.all
user.each do |user|
ArticleNotificationMailer.new_article(user, self).deliver_now
end
end
Upvotes: 0
Reputation: 447
ArticleNotificationMailer.new_article(@user, @article).deliver
Seems like @user was initialized by User.where() in your controller. User.where returns an instance of User::ActiveRecord_Relation which is in fact rails-enhanced array. And errors comes up when you are trying to call email on this array.
Just use User.find if you need to find only one record.
Upvotes: 1
Reputation: 10111
Try passing in the id of the elements.
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
Upvotes: 0