0

我的 Rails 应用程序的用户收到了很多电子邮件(假设它们代表我用户的新客户的注册)。收到电子邮件后,应创建一个客户,并保存该电子邮件。但是,如果客户已经存在(通过电子邮件的电子邮件地址识别),则不应将电子邮件电子邮件保存到数据库中。我认为这是由 处理的Email.new,然后只有save在电子邮件地址被识别的情况下。但似乎Email.new将记录保存到数据库中。那么,在实际决定是否要保存电子邮件之前,我该如何处理它呢?

示例代码:

class Email
  include Mongoid::Document

  field :mail_address, type: String
  belongs_to :user,     :inverse_of => :emails
  belongs_to :customer, :inverse_of => :emails

  def self.receive_email(user, mail)
    puts user.emails.size                                                  # => 0
    email = Email.new(mail_address: mail.fetch(:mail_address), user: user) # Here I want to create a new instance of Email without saving it
    puts user.emails.size                                                  # => 1
    is_spam = email.test_if_spam
    return is_spam if is_spam == true
    is_duplicate = email.test_if_duplicate(user)
  end

  def test_if_spam
    spam = true if self.mail_address == "spam@example.com"
  end

  def test_if_duplicate(user)
    self.save
    customer = Customer.create_or_update_customer(user, self)
    self.save if customer == "created"                                     # Here I want to save the email if it passes the customer "test"
  end
end

class Customer
  include Mongoid::Document

  field :mail_address, type: String
  belongs_to :user, :inverse_of => :customers
  has_many :orders, :inverse_of => :customer

  def self.create_or_update_customer(user, mail)
    if user.customers.where(mail_address: mail.mail_address).size == 0
      customer = mail.create_customer(mail_address: mail.mail_address, user: user)
      return "created"
    end
  end
end
4

1 回答 1

0

我将建议对您的功能进行一些基本的改造。尝试像这样重写你的函数:

class Email
  def self.save_unless_customer_exists(user, mail)
    email = Email.new(
      mail_address: mail.fetch(:mail_address),
      user: user
    )
    return if email.customer or email.is_spam? or email.is_duplicate?
    Customer.create!(user: user)
    email.save!
  end
end

您将无法将该代码放入并期望它工作,因为您必须定义is_spam?and is_duplicate?,但希望您至少可以看到我来自哪里。

如果您还没有,我还建议您为这些功能编写一些自动化测试。它将帮助您确定问题所在。

于 2013-05-09T18:30:55.350 回答