【问题标题】:Manually Send Email Rails手动发送电子邮件 Rails
【发布时间】:2023-03-26 01:41:01
【问题描述】:

我一直在尝试实现这个问题的代码:Send an email manually of a specific page in rails app

唯一的区别是我需要从我的模型中获取电子邮件地址。这在从模型发送电子邮件时通常没有问题。

UserMailer.report(self).deliver

但我想在我的记录的显示视图中单击一个按钮。

我需要使用电子邮件中记录的详细信息手动发送电子邮件。

也许有比为此使用额外的控制器更好的方法?

# app/mailers/user_mailer.rb
class UserMailer < ActionMailer
  def report(thing)
    @thing = thing
    mail :to => thing.email, :from => 'you@example.com', 
      :subject => 'that report you want'
  end
end

# app/views/user_mailer/report.html.erb
<h1>Report</h1>
<p>Here is your <% @thing.customer_id %></p>


# app/controllers/reports_controller.rb
def create
  UserMailer.report(@thing).deliver
  flash[:notice] = 'report sent!'
  redirect_to root_path # or wherever
end

# in a view
<% form_tag(reports_path(@thing), :method => :post) do %>
  <% submit_tag 'send report email' %>
<% end %>

我用上面的代码返回 null:

ArgumentError (wrong number of arguments (0 for 1)):
app/controllers/reports_controller.rb:3:in `create'

【问题讨论】:

    标签: ruby-on-rails ruby email


    【解决方案1】:

    Create是rails中的一个post请求,你不能传递这样的参数,你需要从params中获取。我看到你给它一个错误的参数。

    其次,你正在做@thing = thing,然后你正在发送东西(没有@)到 UserMailer 的报告方法,这也是错误的,它在报告方法中将是 nil。你应该在 @thing 是一个有电子邮件的对象之后做 UserMailer.report(@thing).deliver

    【讨论】:

    • 如何从参数中获取?
    • 因此,当调用 create 操作时,这意味着正在从视图提交一些表单并且正在创建某些内容,并且您可以在 create 操作中使用 p 参数看到该表单参数。 def create 中下一行的 p 参数也是如此。您将在 rails 服务器日志中看到报告的参数。然后创建@report = Report.new(params[:report]);报告.保存。如果报告对象中存在电子邮件,请执行此 UserMailer.report(@report).deliver
    • 请查看第 4 点参数中的这个参数以了解操作及其工作方式。我想它会帮助你guides.rubyonrails.org/action_controller_overview.html
    猜你喜欢
    • 1970-01-01
    • 2014-07-06
    • 2011-10-25
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多