0

找不到得到這個很容易做到 我想拿出以下問題數據庫模型中的最佳途徑。如何添加驗證,以軌道模型依賴於其他模型

有是有一個相關帳戶表Deal表。每個帳戶可以有多個聯繫人。現在,一筆交易需要分配主要聯繫人,該主要聯繫人必須是關聯帳戶的多個聯繫人中的一個。如何確保主要聯繫人是其中一個帳戶聯繫人。

Deal Table 
    account_id 
    primary_contact_id 

Account Table 
    name and other params 

Contact Table 
    account_id 
    phone, email etc. 

例如,類我使用目前

class Deal < ActiveRecord::Base 
    belongs_to :account 
    belongs_to :contact 
end 

class Account < ActiveRecord::Base 
    has_many :contacts 
    has_many :deals 
end 

class Contact < ActiveRecord::Base 
    belongs_to :account 
    has_many :deals 
end 

我可以在交易模型或控制器添加驗證,以確保得到補充說,接觸是其帳戶中的聯繫人當中的一個。但如何採取下列情況的護理:

  1. 刪除從帳戶的聯繫人應當確保交易表的相應CONTACT_ID設爲零
  2. 刪除與交易相關聯的賬戶應該確保CONTACT_ID該交易表是無效
  3. 更新賬戶協會應確保交易的CONTACT_ID是無效。

回答

0

可能是你可以使用模型回調,例如:您的答覆

class Deal < ActiveRecord::Base 
    belongs_to :account 
    belongs_to :contact 

    before_update :nullify_contact_association, :if => lambda{|i| i.account_id_changed?} 

    private 
    # Nullify contact_id of the deal if it's account association was changed 
    def nullify_contact_association 
    self.contact_id = nil 
    end 
end 

class Account < ActiveRecord::Base 
    has_many :contacts 
    has_many :deals 

    before_destroy :nullify_dependencies 

    private 

    #Deleting an account associated with a deal should 
    #make sure that contact_id of that deal table is nullified 
    def nullify_dependencies 
    self.deals.update_all(:contact_id => nil) if deal.present? 
    end 
end 

class Contact < ActiveRecord::Base 
    belongs_to :account 
    has_many :deals 

    before_destroy :nullify_dependencies 

    private 

    #Deleting a contact from an account should make sure 
    #that corresponding contact_id of the deal table is set to nil 
    def nullify_dependencies 
    self.deals.update_all(:contact_id => nil) if account.present? 
    end 
end 
+0

謝謝,我以類似的方式嘗試它,並得到它的工作。 –

0
class Deal 

    validate :contact_is_among_the_contacts_in_associated_account 

    private 

    def contact_is_among_the_contacts_in_associated_account 
    errors.add(:contact_id, "Your error message") unless contact.in?(account.contacts) 
    end 

end 
+0

感謝。我嘗試了這種方式,但問題是我問過上述 假設處理ID 1已經ACCOUNT_ID 1,這與IDS 1和2。現在我指定交易的主要聯繫人的聯繫人2聯繫人的問題之一。之後,如果我們從聯繫人表中刪除聯繫人2,交易表將保持account_id 1和primary_contact_id爲2.這可能已被忽略,因爲deal.primary_contact返回nil並沒有問題。但問題是,現在我們無法對交易進行任何其他編輯(如更改名稱),因爲所有進一步的編輯都將通過此驗證被阻止。 –

+0

可能我可以通過確保primary_contact_id設置爲nil來解決此問題,只要與該ID的聯繫人從數據庫中刪除。此外,我必須確保每當帳戶被刪除時,primary_contact_id和account_id都將被取消。如何在rails中實現這一點? –