2013-05-09 27 views
0

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

你確定'.new'是保存'email'記錄嗎?如果你進入控制檯並輸入Email.new(mail_address:「[email protected]」,user:user.first).new_record?',你會得到'true'還是'false'?如果你得到'假',真的很奇怪。但我敢打賭你會變得真實,而這個問題就在別處。 – 2013-05-09 18:02:17

+0

嗨Jason。謝謝你的評論。我剛剛在碼頭登記,你100%正確。它返回'true'。但是,請查看我在代碼中編輯的內容。當''放在'Email.new'之前的電子郵件數量時,它返回'0',但是當''放入'之後,它返回'1'。 – ChristofferJoergensen 2013-05-09 18:16:00

回答

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?is_duplicate?,但我希望你至少可以看到我來自。

如果您還沒有,我還建議您爲這些功能編寫一些自動化測試。它將幫助你確定問題。

+0

謝謝你的回答傑森。你能否詳細說明這將如何避免將電子郵件保存到數據庫?據我所見,問題在於在第一行使用'Email.new'。 – ChristofferJoergensen 2013-05-09 18:45:10

+0

好問題。這並不直接解決這個問題。我的經驗是,簡單的代碼更容易調試,所以我認爲,第一步可能是簡化代碼。 (即使簡化本身不能修復這個bug,這也是一個好主意。) – 2013-05-09 18:53:18

相關問題