想了解如何将多个对象传递到rails中的动作邮件程序/电子邮件内容。我没有在@announcement中传递任何问题,但不知道如何传入@ post和@user信息。
announcement_controllers.rb
def create
@post = Post.find_by slug: params[:post_id]
@announcement = @post.announcements.build(announcement_params)
@announcement.creator = current_user
if @announcement.save
flash[:notice] = 'Your announcement was created.'
AnnouncementMailer.announcement_alert(@announcement, @post).deliver
redirect_to :back
else
flash[:notice] = 'Unable to create announcement. Make sure you have enter information.'
redirect_to :back
end
end
announcement_mailer.rb
class AnnouncementMailer < ActionMailer::Base
binding.pry
default to: Proc.new { Signup.where(post_id: @post.id, user_id: current_user.id).pluck(:email) },
from: "#{@post.slug}@fundspace.announcement.com"
def announcement_alert(announcement, post)
@announcement = announcement
@post = post
mail(subject: "#{@post.slug}: #{@announcement.title}")
end
end
binding.pry
1: class AnnouncementMailer < ActionMailer::Base
=> 2: binding.pry
3: default to: Proc.new { Signup.where(post_id: @post.id, user_id: current_user.id).pluck(:email) },
4: from: "#{@post.slug}@fundspace.announcement.com"
5:
6: def announcement_alert(announcement, post)
7: @announcement = announcement
[1] pry(AnnouncementMailer)> @post
=> nil
[2] pry(AnnouncementMailer)> @announcement
=> nil
[3] pry(AnnouncementMailer)> @user
=> nil
binding.pry检查announcement_mailer.rb中的@post返回nil。不知道为什么。提前谢谢。
答案 0 :(得分:0)
这是您的调试代码的经典案例,给您错误的印象。您的@post
已经过好了 - 但在调用binding.pry
后正在发生。
您将post
传递给announcement_alert
,将其设置为实例变量。如果您将该方法更新为这样,您应该看到它设置正常:
def announcement_alert(announcement, post)
@announcement = announcement
@post = post
binding.pry
mail(subject: "#{@post.slug}: #{@announcement.title}")
end
(您不会检查post
是否是邮件中的对象,因此其他代码可以通过nil
。这不应该是但是,在这种情况下,问题是Post.find_by
如果没有匹配则会返回nil
,但如果有@post.announcements.build
则会失败。)
对@post
设置位置的这种混淆也会导致default
行出现问题。方法之外的语句 - 例如binding.pry
和default to:
- 在评估类时运行。方法内的语句 - def announcement_alert
内的语句 - 在调用该方法之前不会运行。而且,正如我们上面所见,@post
在您致电announcement_method
之前未定义。
这是您当前的default
声明:
default to: Proc.new { Signup.where(post_id: @post.id, user_id: current_user.id).pluck(:email) },
from: "#{@post.slug}@fundspace.announcement.com"
您的to:
参数设置为Proc
,这很棒 - 即使它引用了@post
,因为它Proc
它没有@post
。直到它需要为止。您此时已设置from:
。
另一方面,您的@post.slug
参数只是一个字符串。它在一个过程之外。因此,它会立即尝试评估@post
- 并且尚未设置default to: Proc.new { Signup.where(post_id: @post.id, user_id: current_user.id).pluck(:email) },
from: Proc.new { "#{@post.slug}@fundspace.announcement.com" }
,从而导致错误。将其更改为此修复它:
{{1}}