我的 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