【问题标题】:Ruby on Rails: Passing parameters to a method under class <<selfRuby on Rails:将参数传递给类 <<self 下的方法
【发布时间】:2017-01-17 10:21:02
【问题描述】:

我在将数据从控制器传递到 class &lt;&lt;self 下的方法时遇到问题,由于某种原因,我不断收到错误 wrong number of arguments (0 for 1) 并且无法弄清楚为什么会收到此错误或如何解决它。

我的 app/controllers/emails_controller 代码是:

def create
    # Make a new email
    @email = Email.new(email_params)
    # For the email, store the user id as the id of the user logged in
    @email.user_id = session[:user_id]  
    # store the user id
    @user = session[:user_id]
    # if the email has saved in the database
    if @email.save
        email_to_name = @email.to_name
        # split the email addresses selected by the ";"
        @emails = (email_params[:to]).split("; ")
        # for each email address selected do the following
        @emails.each do |emailaddress|
            # the "to" section of the email is to one email address
            @email.to = emailaddress
            # find who to address the email to using the Contact model
            @email.to_name = address_email_to(email_to_name, @email.prefix, emailaddress)
            # find the contact the user wants to email
            contact = Contact.find_by_email(emailaddress).id
            # generate a unsubscribe token
            @unsubscribe = Rails.application.message_verifier(:unsubscribe).generate(contact)       
            # PASS THE ACCOUNT ID TO THE SMTP SETTINGS METHOD IN MY MAILER
            UserEmails.smtp_settings(@email.account_id)
            # send the email
            UserEmails.send_email(@email, @unsubscribe, @email.logo).deliver_now
        end
        # show the email
        redirect_to @email, notice: 'Email was successfully created.'
    # if not saved
    else
        # go back to the new email page
        redirect 'new'
    end
  end

private 
def email_params 
    res = params.require(:email).permit(:account_id, :cc, :bcc, :subject, :greeting, :to_name, :prefix, :message, :from_name, :logo, to: []) 
    res[:to] = res[:to].join('; ')
    res 
end

而我的 app/mailers/user_emails.rb 是:

class UserEmails < ApplicationMailer

    if Rails.env.development?
        class <<self
          def smtp_settings(account)
            options = YAML.load_file("#{Rails.root}/config/mailers.yml")[Rails.env]['send_email']
            @@smtp_settings = {
              :address              => 'smtp.gmail.com',
              :port                 => 587,
              :domain               => 'my-domain.com',
              :authentication       => 'plain',
              # FIND THE USER-NAME IN THE ACCOUNT MODEL
              :user_name            => Account.find_by_id(account).email,
              :password             => 'my password', 
            }
          end
        end
    end
    def send_email(email, unsubscribe, logo)
        @url  = 'http://localhost:3000/users/login'
        @email = email
        @unsubscribe = unsubscribe
        @logo = logo
        mail(from: "#{@email.from_name} <#{@email.account.email}>", to: @email.to, cc: @email.cc, bcc: @email.bcc, subject: @email.subject, message: @email.message)
    end
end

日志如下:

Started POST "/emails" for ::1 at 2016-09-09 11:11:15 +0100
Processing by EmailsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"rCvqJpUNAMker3u6R5sOLjP317oN33t7LSAbJoul1nNkfRt/WwJYT+4vS/fmNW37/XzSOREqafIj/Dqf1k330Q==", "email"=>{"from_name"=>"Ben Smith", "account_id"=>"30", "to"=>["email@gmail.com", ""], "logo"=>"", "subject"=>"", "greeting"=>"No Greeting", "to_name"=>"No Name", "prefix"=>"No", "message"=>""}, "commit"=>"Create Email"}
  [1m[35m (0.0ms)[0m  begin transaction
  [1m[36mSQL (1.0ms)[0m  [1mINSERT INTO "emails" ("account_id", "subject", "greeting", "to_name", "prefix", "message", "from_name", "logo", "to", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)[0m  [["account_id", 30], ["subject", ""], ["greeting", ""], ["to_name", "No Name"], ["prefix", "No"], ["message", ""], ["from_name", "Ben Smith"], ["logo", ""], ["to", "email@gmail.com; "], ["user_id", 2], ["created_at", "2016-09-09 10:11:15.382459"], ["updated_at", "2016-09-09 10:11:15.382459"]]
  [1m[35m (205.0ms)[0m  commit transaction
  [1m[36mContact Load (0.0ms)[0m  [1mSELECT  "contacts".* FROM "contacts" WHERE "contacts"."email" = ? LIMIT 1[0m  [["email", "email@gmail.com"]]
  [1m[35mAccount Load (0.0ms)[0m  SELECT  "accounts".* FROM "accounts" WHERE "accounts"."id" = ? LIMIT 1  [["id", 30]]

UserEmails#send_email: processed outbound mail in 6.0ms
Completed 500 Internal Server Error in 234ms (ActiveRecord: 206.0ms)

ArgumentError (wrong number of arguments (0 for 1)):
  app/mailers/user_emails.rb:5:in `smtp_settings'
  app/mailers/user_emails.rb:34:in `send_email'
  app/controllers/emails_controller.rb:58:in `block in create'
  app/controllers/emails_controller.rb:46:in `each'
  app/controllers/emails_controller.rb:46:in `create'


  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (4.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (1470.1ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (13.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (1370.1ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (3191.2ms)

对于背景信息,我正在尝试更改每个登录用户的 SMTP 服务器设置,并且我正在通过更改用户名设置来测试这是否可行 - 如果可行,那么我打算还为每个用户配置其他 smtp 设置。例如。系统为每个用户存储一个地址、端口、域、认证用户名和密码,当用户 1 发送电子邮件时,这些都根据他们的设置进行配置,当用户 2 发送电子邮件时,这些都根据他们的设置进行配置。我现在只包含用户名作为测试,看看这个理论是否可行。

有人可以帮我解决我的问题吗?

【问题讨论】:

  • 介意发布堆栈跟踪的前 5-7 行吗?
  • app/mailers/user_emails.rb:34 中的send_email 方法中,您可以在不带参数的情况下调用此smtp_settings。控制器可能与问题无关。
  • 好的,我也加入了send_email方法,但我不明白这会是什么问题?
  • 第 34 行是哪一行?此外,您还包含了实例方法send_mail,而有问题的是类方法。
  • 线路是email(from: "#{@email.from_name} &lt;#{@email.account.email}&gt;", to: @email.to, cc: @email.cc, bcc: @email.bcc, subject: @email.subject, message: @email.message)

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


【解决方案1】:

如果我错了,我不会,但在你的控制器代码中 @email = Email.new(email_params)

你还没有定义你的 email_params,因为我想它是你定义的参数。

【讨论】:

  • 我在这里看不到 email_params 的相关性,不过我现在已将它们包含在我的问题中。
【解决方案2】:

smtp_settings 方法已在 ActionMailer 中定义为具有 0 个参数的方法。您将其重新定义为具有 1 个参数的方法。这会导致当前错误 app/mailers/user_emails.rb:34:insend_email'.mailmethod is callingsmtp_settings` 没有任何参数。一种解决方案是将您的方法重命名为不会与 ActionMailer 中可用的现有方法发生冲突的方法。但我觉得这种做法不好。

您可以做的是将您的 SMTP 设置作为 delivery_method_options 哈希传递给 mail 方法。这是一个例子

def send_email(email, unsubscribe, logo)
  @url  = 'http://localhost:3000/users/login'
  @email = email
  @unsubscribe = unsubscribe
  @logo = logo

  account = Account.find_by_id(email.account)
  # You can change here all SMTP settings
  delivery_method_options = {
    :address              => 'smtp.gmail.com',
    :port                 => 587,
    :domain               => 'my-domain.com',
    :authentication       => 'plain',
    :user_name            => account.email,
    :password             => 'my password', 
  }

  mail(
    from: "#{@email.from_name} <#{@email.account.email}>",
    to: @email.to,
    cc: @email.cc,
    bcc: @email.bcc,
    subject: @email.subject,
    message: @email.message,
    delivery_method_options: delivery_method_options
  )
end

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 2013-03-24
相关资源
最近更新 更多