我的最终目标是在创建故障单时发送电子邮件。当我使用我手动键入的一个电子邮件地址时,它工作得很好但是当我尝试通过数据库来提取已注册用户的电子邮件地址时,我收到一条错误消息:未定义的方法`email'为零:NilClass
我确信这是一个简单的解决方案,但我一直迷路并进入圈子。以下是我所处的代码 - Ticket Controller:
def create
@ticket = Ticket.new(params[:ticket])
respond_to do |format|
if @ticket.save
TicketMailer.ticketcreated_email(@user).deliver
format.html { redirect_to @ticket, notice: 'Ticket was successfully created.' }
format.json { render json: @ticket, status: :created, location: @ticket }
else
format.html { render action: "new" }
format.json { render json: @ticket.errors, status: :unprocessable_entity }
end
end
end
ticket_mailer.rb
class TicketMailer < ActionMailer::Base
default :from => "myemailaddress@gmail.com"
def ticketcreated_email(user)
mail(:to => user.email, :subject => "Simple Test")
end
end
邮件文件/ etc全部如果我只用我的电子邮件地址替换ticket_mailer.rb中的“user.email”。但是,只要我找到使用Devise构建的用户,我就无法获取他们的数据。
答案 0 :(得分:0)
您希望将电子邮件发送给当前用户吗?您可以尝试:
TicketMailer.ticketcreated_email(current_user).deliver
或者,如果您想为每个用户提供自定义电子邮件,您可能需要循环:
users=User.all
users.each do |user|
mail(:to => user.email, :subject => "Simple Test")
end
在控制器和类之间拆分工作可能如下所示:
控制器:
if @ticket.save
users=User.all
users.each do |user|
TicketMailer.ticketcreated_email(user).deliver
end
format.html { redirect_to @ticket, notice: 'Ticket was successfully created.' }
类别:
def ticketcreated_email(user)
mail(:to => user.email, :subject => "Simple Test")
end
答案 1 :(得分:0)
由于@cschroed
,我最终得到了这个过程def create
@ticket = Ticket.new(params[:ticket])
respond_to do |format|
if @ticket.save
user=User.all
user.each do |user|
TicketMailer.ticketcreated_email(user).deliver
end
format.html { redirect_to @ticket, notice: 'Ticket was successfully created.' }
format.json { render json: @ticket, status: :created, location: @ticket }
else
format.html { render action: "new" }
format.json { render json: @ticket.errors, status: :unprocessable_entity }
end
end
end