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中实现这一点? –