我的Rails應用程序的用戶正在接收大量電子郵件(可以說它們代表來自我的用戶的新客戶的註冊)。當收到電子郵件時,應該創建一個客戶,並且該電子郵件也應該保存。但是,如果客戶已經存在(通過電子郵件的電子郵件地址識別),則不應將電子郵件電子郵件保存到數據庫。我認爲這是由Email.new
處理,然後只有save
如果電子郵件地址被識別。但似乎Email.new
將記錄保存到數據庫。那麼在實際決定我想保存它之前,我如何使用電子郵件?如何使用模型的實例而不將其保存到mongoid
示例代碼:
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 == "[email protected]"
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
你確定'.new'是保存'email'記錄嗎?如果你進入控制檯並輸入Email.new(mail_address:「[email protected]」,user:user.first).new_record?',你會得到'true'還是'false'?如果你得到'假',真的很奇怪。但我敢打賭你會變得真實,而這個問題就在別處。 – 2013-05-09 18:02:17
嗨Jason。謝謝你的評論。我剛剛在碼頭登記,你100%正確。它返回'true'。但是,請查看我在代碼中編輯的內容。當''放在'Email.new'之前的電子郵件數量時,它返回'0',但是當''放入'之後,它返回'1'。 – ChristofferJoergensen 2013-05-09 18:16:00