2017-02-21 23 views
0

A具有可被軟刪除的具有電子郵件唯一性的聯繫人模型。Rails在保存時替換ApplicationRecord實例

我希望當有人試圖用某個soft_deleted聯繫人拍攝的電子郵件創建聯繫人時,這個新實例將成爲軟刪除記錄。

一個例子,以明確

contact = Contact.new(email: '[email protected]') 
contact.save # this got id = 1 
contact.soft_destroy 

# I expect contact2 to have id 1 
contact2 = Contact.new(email: '[email protected]') 
contact2.save 

# I was able to do it with create 

PS:我其實創建聯繫人爲nested_attributes,所以如果我能做到這一點怪異另存爲其中的一部分,這將是巨大的。

事件的has_many邀請HAS_ONE聯繫

我得到的最接近是這樣的:

class Event < ApplicationRecord 
    accepts_nested_attributes_for :invites 

    before_save :restore_contacts 

    def restore_contacts 
    invites.each do |invite|  
     restorable_contact = Contact.find_by_email invite.contact.email 
     invite.contact = restorable_contact if restorable_contact 
    end 
    end 
end 

但它提出了在此之前的方法運行:(

+0

我想,當聯繫人存在'restore_contacts'的作品,我說得對嗎?你能解釋一下「我離開的最近」是什麼意思? – rogelio

+0

Ops,我的不好,請參閱編輯 –

+0

您是否在使用某些特定的gem進行軟刪除? – rogelio

回答

0

至於你說對接觸的驗證錯誤,解決你必須做的第一部分(也許不是最好的選擇,但我試圖解釋邏輯):

在你的Contact米奧德爾

# app/models/contact.rb 
class Contact < ApplicationRecord 
    validates :email, uniqueness: true 
    ... 
    def restore 
    self.update_attribute deleted_by_user_at, nil 
    # other actions ... 
    end 
    ... 
end 

然後,您可以執行以下操作:

contact = Contact.find_or_initialize_by email: "[email protected]" 

if contact.persisted? 
    # email exists as Contact on DB 
    # it needs some extra validation 
    if contact.deleted_by_user_at.nil? 
    # email is already in use 
    else 
    # contact was soft deleted 
    contact.restore 
    end 
else 
    # email is free to use 
    contact.save 
end 

如果你確實需要使用nested_attributes你將不得不更改/添加代碼,但邏輯是一樣的