为什么我会得到“未定义的方法`编码'”?

时间:2013-07-25 09:31:45

标签: ruby-on-rails ruby-on-rails-3 actionmailer

为什么我会得到“未定义的方法`编码'”? 我该如何解决这个问题?

错误消息

NoMethodError (undefined method `encoding' for #<Array:0x000000218f61e8>):
 app/controllers/messages_controller.rb:255:in `deliver'

messages_controller.rb

# coding: UTF-8

class MessagesController < ApplicationController

    deliver
        users = User.confirmed.order("created_at ASC")

        @users_emails = []          
        users.each do |user|
            @users_emails += [user.email]
        end

        subject = params[:messages][:subject] 
        body = params[:messages][:body]

        CallMailer.call_email(@users_emails, subject, body).deliver  <= This is line 255  
    end

end

寄件人/ call_mailer.rb

# coding: UTF-8

class CallMailer < ActionMailer::Base

    default :from => "dont-reply@example.com"

    def call_email(users_emails, mesesage_subject, mesesage_body)
        @users_emails = users_emails
        @mesesage_subject = mesesage_subject
        @mesesage_body = mesesage_body
        mail(
            :bcc => @users_emails,
            :subject => @mesesage_subject,
            :body => @mesesage_body) do |format|
            format.html
        end
    end

end

3 个答案:

答案 0 :(得分:10)

我发现你正在为bcc获得正确的数组,可能你有一些错误的电子邮件地址。

当电子邮件地址在@之前包含一个点时,例如test。@ test.com,并作为数组的一部分提交,您将获得一个未定义的方法`encoding'for Array。该错误仅出现在Ruby 1.9中,并且只有在地址作为数组提交时才会出现。

试试这个

def call_email(users_emails, mesesage_subject, mesesage_body)
        @users_emails = users_emails
        @mesesage_subject = mesesage_subject
        @mesesage_body = mesesage_body
        mail(
            :bcc => @users_emails.join(','),
            :subject => @mesesage_subject,
            :body => @mesesage_body) do |format|
            format.html
        end
    end

答案 1 :(得分:3)

CallMailer中你因为:bcc只使用字符串而不是数组

你能这样做吗

@user_emails.each do |email|     
  mail(
        :bcc => email,
        :subject => @mesesage_subject,
        :body => @mesesage_body) do |format|
        format.html
    end 
end  

感谢

答案 2 :(得分:2)

实际上bcc看起来像这样

 mail(:to => "rails@example.com" ,  :subject => "Example Rails"
 :bcc => ["bcc@rails.com", "Rails Group <railsgroup@example.com>"] ,
 :cc => "other@example.com" )

所以你可以做一件事使bcc成为bcc = []
@user_emails.each do |email|
bcc << email + "," end

    mail(:to => "rails@example.com",:subject => "Example Rails", :bcc => bcc, :cc => "other@example.com" ) 

由于