未定义的局部变量或方法`params' - 在梅勒

时间:2015-10-09 05:23:07

标签: ruby-on-rails ruby-on-rails-4

故事:

当用户点击“喜欢”之类的时候会发生这种情况。用户帖子上的按钮会向帖子所有者发送通知。每个帖子的路线如class PostNotification < ActionMailer::Base default :from => 'no-reply@example.com' def send_notification_email(user) user = User.friendly.find( params[:user_id] ) # params only work in the views/controller. How to get it to work here?? mail( :to => user.email, # should send to that particular post owner :subject => "You've got a post like" ) end end

假设:SendGrid已配置且工作正常。

生成发布通知:

<!DOCTYPE html> <html> <head> <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' /> </head> <body> <h1>You've got a new like from, <%= current_user.name %>!</h1> <p>Blaahhhhhh</p> </body> </html>

在app / mailers / post_notification.rb中:

class PostsController < ApplicationController

  def like
   [...] # other working code
   if p.save
    PostNotification.send_notification_email(@user).deliver
  end

end

应用/视图/ post_notification / send_notification_email.html.erb

user_id

应用/控制器/ posts_controller:

post_notification.rb

想法是抓取该帖子的{{1}},以便通知/电子邮件从(current_user)发送到该用户,并在正文中显示消息。我遇到的麻烦在于{{1}}。如何获取该帖子的所有者&#39;电子邮件发给他们了?

2 个答案:

答案 0 :(得分:2)

ActionMailer 无法访问控制器params,因此您无法在邮件中访问params哈希。

您可以将所需的参数作为参数传递,就像您通过user方法中的参数中的send_notification_email一样。如果您需要,请使用该用户的ID:

def send_notification_email(user)
  user = User.friendly.find(user.id) # use the id of the passed user
  mail( :to => user.email,
        :subject => "You've got a post like" )
end

显然,您甚至可以省略user = User.friendly.find(user.id) # use the id of the passed user行,因为您已经拥有user对象,您可以在mail方法调用中直接使用该对象:

def send_notification_email(user)
  mail(:to => user.email,
        :subject => "You've got a post like")
end

这两个都应该有用。底线是: ActionMailer 无法访问导致错误的控制器params哈希。 : - )

答案 1 :(得分:1)

您实际上不需要此行user = User.friendly.find( params[:user_id] )。您在@user处将send_notification_email(@user)作为参数传递,因此user中的mailer method访问它。以下应该有效。

class PostNotification < ActionMailer::Base

  default :from => 'no-reply@example.com'

  def send_notification_email(user)
    mail( :to => user.email, :subject => "You've got a post like" )
  end
end