【问题标题】:NoMethodError: undefined method `mail' for main:Object on rails consoleNoMethodError:未定义方法'mail'的main:rails控制台上的对象
【发布时间】:2017-03-01 18:46:30
【问题描述】:

我正在尝试测试邮件程序的工作。通常在 Rails 上,我首先在控制台级别测试我的代码逻辑,然后一旦成功,我将其放入真正的源代码中。我正在尝试在 ApplicationMailer 上做同样的事情。我遵循了其他一些解决方案,首先在 Rails 控制台上运行以下命令来首先设置 ActionMailer

ActionMailer::Base.delivery_method = :smtp 
ActionMailer::Base.smtp_settings = {
  address: 'smtp.gmail.com', 
  port: 587, 
  domain: 'gmail.com',
  authentication: 'plain', 
  enable_starttls_auto: true, 
  user_name: '***********',
  password: '******'
}

然后我运行我的代码:

y.include? x
  if true
    @receiver = Model.where(category_id: "#{x}").pluck(:email)
    mail(to: @receiver, subject: @subject)
  end

我收到以下错误:

NoMethodError: undefined method `mail' for main:Object
    from (irb):19

有人可以告诉我如何在 Rails 控制台上进行这项工作吗?

【问题讨论】:

  • 邮件中有mail(to: @receiver, subject: @subject)这行吗?
  • 或者直接在控制台上运行
  • 你有这个邮件吗?
  • 我首先尝试在控制台上运行它

标签: ruby-on-rails ruby actionmailer


【解决方案1】:

您可以使用以下方式测试邮件

ActionMailer::Base.mail(from: "test@example.co", to: @receiver, subject: @subject, body: "Test").deliver

【讨论】:

【解决方案2】:

Rails 设置了很多便利,因此您可以例如轻松从控制器发送邮件。

在控制台中,您不在控制器的上下文中,因此您还没有设置它。视图助手也是如此。

为了使用 mail-method,你需要告诉 Ruby 在哪里寻找它。

这样发送邮件应该足够了:

ActionMailer::Base.mail(from: "test@example.co", to: @receiver, subject: @subject, body: "Test").deliver

请记住,如果您只想测试邮件生成,但还没有与您的 SMTP 集成,您也可以使用不同的 delivery_methods。

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    相关资源
    最近更新 更多