ruby-on-rails - 找不到没有 ID 的用户,通知程序
问题描述
我正在发送带有消息和主题的简单邮件,当我想将邮件发送到目标邮件时,我收到以下错误,“找不到没有 ID 的用户”
我有以下代码:
应用程序/邮件程序/notifier.rb:
def envio_mail(subject, message, user)
@user = User.find(user)
@muser = user
@body_message = message
mail(:to => @user.email, :subject => subject)
end
应用程序/控制器/gratitudes_controller.rb:
def create
@gratitude = Gratitude.new(params[:gratitude])
user = params[:user_id]
Notifier.envio_mail(params[:subject], params[:message], user).deliver
respond_to do |format|
if @gratitude.save
format.html { redirect_to(@gratitude, :notice => 'Gratitude was successfully created.') }
format.xml { render :xml => @gratitude, :status => :created, :location => @gratitude }
else
format.html { render :action => "new" }
format.xml { render :xml => @gratitude.errors, :status => :unprocessable_entity }
end
end
end
这是错误:
Started POST "/gratitudes" for 127.0.0.1 at 2020-02-26 17:10:55 -0500
Processing by GratitudesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"iofCtlwd5CE5Zbuo5n6NzCo4Inksht4o05OiiwYUY24=", "gratitude"=>{"subject"=>"asdasd", "message"=>"<p>asda</p>", "user_id"=>"4"}, "commit"=>"Enviar mensaje"}
SCHEMA (0.6ms) SHOW TABLES
ClientParameterization Load (0.2ms) SELECT `client_parameterizations`.* FROM `client_parameterizations` LIMIT 1
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
Profile Load (0.2ms) SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`id` = 1 LIMIT 1
Completed 404 Not Found in 130ms
ActiveRecord::RecordNotFound (Couldn't find User without an ID):
app/mailers/notifier.rb:405:in `envio_mail'
app/controllers/gratitudes_controller.rb:48:in `create'
解决方案
在你的参数中"gratitude"=>{"subject"=>"asdasd", "message"=>"<p>asda</p>", "user_id"=>"4"}
user_id
嵌套在里面gratitude
,这样做是为了获取user_id
user = params[:gratitude][:user_id]
建议
为确保仅在成功创建 Gratitude 时发送邮件,您可以将邮件触发器移动到模型中的after_commit
回调Gratitude
在感恩模型中
after_commit :send_mail, on: :create
def send_mail
Notifier.envio_mail(subject, message, user_id).deliver
end
希望有帮助!